How to make correct date format when writing data to Excel

后端 未结 10 1931
[愿得一人]
[愿得一人] 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:07

    Old question but still relevant. I've generated a dictionary that gets the appropriate datetime format for each region, here is the helper class I generated:

    https://github.com/anakic/ExcelDateTimeFormatHelper/blob/master/FormatHelper.cs

    FWIW this is how I went about it:

    1. opened excel, manually entered a datetime into the first cell of a workbook
    2. opened the regions dialog in control panel
    3. used Spy to find out the HWND's of the regions combobox and the apply button so I can use SetForegroundWindow and SendKey to change the region (couldn't find how to change region through the Windows API)
    4. iterated through all regions and for each region asked Excel for the NumberFormat of the cell that contained the date, saved this data to into a file

提交回复
热议问题