How to make correct date format when writing data to Excel

后端 未结 10 1922
[愿得一人]
[愿得一人] 2020-11-30 04:56

Iam exporting a DataTable to an Excel-file using office interop. The problem is, that Excel does not recognize dates as such, but instead it displays numbers. In another cas

10条回答
  •  盖世英雄少女心
    2020-11-30 05:06

    Expanding slightly on @Assaf answer, to apply formatting correctly I also had to convert the DateTime via the .ToOADate() function before the formatting took effect. You can do this on a cell by cell basis:

    xlWorkSheet.Cells[Row, Col].NumberFormat = ""; // e.g. dd-MMM-yyyy
    xlWorkSheet.Cells[Row, Col] = DateTimeObject.ToOADate();
    

    Or you can apply the formatting to the entire column:

    xlWorkSheet.Cells[Row, Col].EntireColumn.NumberFormat = ""; // e.g. dd-MMM-yyyy
    xlWorkSheet.Cells[Row, Col] = DateTimeObject.ToOADate();
    

提交回复
热议问题