我正在尝试将SQL数据集导出到excel文档中。
在输出日期字段的某些点处,excel单元格在某些点处被格式化为日期单元格,而某些则被格式化为一般格式。 这导致日期以我想要的格式在某些时候显示,例如英国风格的日/月/年,美国风格的月/日/年。
如果这只是一种方法,那会很好,因为报告至少是一致的。但是,该代码有时会输出正确的格式,有时却不会很烦人的事实
到目前为止,我的代码:
private void doReport(DataSet myDS)
{
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
int i;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "Report produced on the " + System.DateTime.Now.ToString("dd/MM/yyyy");
xlWorkSheet.Cells[3, 1] = "Project Type";
xlWorkSheet.Cells[3, 2] = "Client";
xlWorkSheet.Cells[3, 3] = "Date Started";
xlWorkSheet.Cells[3, 4] = "Target Date";
xlWorkSheet.Cells[3, 5] = "Date Completed";
xlWorkSheet.Cells[3, 6] = "Stage Target";
xlWorkSheet.Cells[3, 7] = "Stage";
xlWorkSheet.Cells[3, 8] = "Assigned To";
xlWorkSheet.Cells[3, 9] = "Notes";
i = 4;
foreach (DataRow row in myDS.Tables[0].Rows)
{
xlWorkSheet.Cells[i, 1] = row["strProjectDescription"];
xlWorkSheet.Cells[i, 2] = row["strClient"];
DateTime dteProjStart = (DateTime)row["dteProjectStart"];
xlWorkSheet.Cells[i, 3] = dteProjStart.ToString("dd/MM/yyyy");
DateTime dteProjTarget = (DateTime)row["dteProjectTarget"];
xlWorkSheet.Cells[i, 4] = dteProjTarget.ToString("dd/MM/yyyy");
if (rbViewProjectsCompletedVal.Checked)
{
DateTime dteProjFin = (DateTime)row["dteProjectFinished"];
xlWorkSheet.Cells[i, 5] = dteProjFin.ToString("dd/MM/yyyy");
}
if (row.IsNull("dteProjectStageTarget") == false)
{
DateTime dteProjStageTar = (DateTime)row["dteProjectStageTarget"];
xlWorkSheet.Cells[i, 6] = dteProjStageTar.ToString("dd/MM/yyyy");
}
xlWorkSheet.Cells[i, 7] = row["strProjectStageDescription"];
xlWorkSheet.Cells[i, 8] = row["initials"];
xlWorkSheet.Cells[i, 9] = csSQL.runSQL("select strProjectNotes from tbl_AdminSupport_Projects where intASProjectID = " + row["intASProjectID"], "Management").Tables[0].Rows[0]["strProjectNotes"];
i++;
}
xlWorkSheet.Columns.AutoFit();
xlWorkSheet.Rows.AutoFit();
xlApp.Visible = true;
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
数据集结构:
任何带有str前缀的项都是nvarchar(max),dte是日期