Excel treating date column as general when exporting to Excel using C#

ぃ、小莉子 提交于 2019-12-11 19:39:09

问题


I am using EPPlus library to export a report in Excel. One of the columns is of date type but after exporting to Excel, when I open that file, it treats that column as "General" unless I right click on it and set its type to "Date".

Following is my code:

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

}

Following is a screenshot as to how this column looks like in Excel.

How can I make sure Excel treat my date column as Date?


回答1:


To Set text as DateTime format in epplus you need to set the format type for a cells

EG:

1) For simple short date Pattern

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

2) If you want specific format like datetime with time,hour etc then

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


来源:https://stackoverflow.com/questions/50384379/excel-treating-date-column-as-general-when-exporting-to-excel-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!