Excel使用C#导出到Excel时将日期列视为常规

时间:2018-05-17 06:05:30

标签: c# excel datatable epplus

我正在使用EPPlus库在Excel中导出报告。其中一列是日期类型,但在导出到Excel后,当我打开该文件时,它会将该列视为" General"除非我右键单击它并将其类型设置为"日期"。

以下是我的代码:

private void ExportToExcel(DataTable dataTable)
{
    //Althought the column type is already date in dataTable but even if I use following line Excel doesn't treat it as Date
    dataTable.Columns["Created On"].DataType = typeof(DateTime);

    foreach (DataRow row in dataTable.Rows)
    {
        row["Created On"] = Convert.ToDateTime(row["Created On"]. 
 ToString()).ToString("yyyy-MM-dd");
    }

    ExcelPackage excel = new ExcelPackage();
    var workSheet = excel.Workbook.Worksheets.Add("MyReport");
    var totalCols = dataTable.Columns.Count;
    var totalRows = dataTable.Rows.Count;
    string fileName = "MyReport[" + DateTime.Now.ToString("yyyy-MM-dd") + "].xlsx";

    for (var col = 1; col <= totalCols; col++)
    {
        workSheet.Cells[1, col].Value = dataTable.Columns[col - 1].ColumnName;
        workSheet.Cells[1, col].Style.Font.Bold = true;
    }

    for (var row = 1; row <= totalRows; row++)
    {
        for (var col = 0; col < totalCols; col++)
        {
            workSheet.Cells[row + 1, col + 1].Value = dataTable.Rows[row - 1][col];
        }
    }
    workSheet.Cells.Style.Font.Size = 11;
    workSheet.Cells.AutoFitColumns();

//Rest of the code

}

以下是关于此列在Excel中的外观的截图。

如何确保Excel将我的日期列视为日期?

enter image description here

1 个答案:

答案 0 :(得分:1)

要在epplus中将文本设置为DateTime格式,您需要设置单元格的格式类型

EG:

1)对于简单的短日期模式

 workSheet.Cells[row, 3].Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.ShortDatePattern;

2)如果你想要特定的格式,如日期时间,时间,小时等,那么

workSheet.Column(dateColIndex).Style.Numberformat.Format = "mm/dd/yyyy hh:mm:ss AM/PM";