My program generates output in Excel.
Some dates seem misinterpreted:

When you open the file, the dates are a mixture, as in the screenshot.
If I actually placed the cursor in the Excel input field (in the fingerprint) and press Enter, the cell formatting will return to the correct formatting.
I use Microsoft.Office.Interop.Excelto move data from a template Datatableto Excelthat saved in my solution.
Before putting data in cells, I change each column number accordingly using switch:
for(int i = 1; i < NumColumns + 1; i++) {
switch(dt.Columns[i-1].DataType.ToString()) {
case "System.Int32":
xlWorkSheet.Columns[i].NumberFormat = "#,##0_ ;[Red]-#,##0 ";
break;
case "System.String":
xlWorkSheet.Columns[i].NumberFormat = "@";
break;
case "System.DateTime":
xlWorkSheet.Columns[i].NumberFormat = "[$-809]dd mmmm yyyy;@";
break;
case "System.Date":
xlWorkSheet.Columns[i].NumberFormat = "[$-809]dd mmmm yyyy;@";
break;
default:
xlWorkSheet.Columns[i].NumberFormat = "@";
break;
}
}
To move values from datatable, I use nested loops:
for(int i = 1; i < NumColumns + 1; i++) {
xlWorkSheet.Cells[1, i].value = dt.Columns[i - 1].ColumnName;
}
DataView dv = new DataView(dt);
dv.Sort = "Date ASC";
int rowCount = 2;
string theValue;
try {
foreach(DataRowView dr in dv) {
for(int i = 1; i < NumColumns + 1; i++) {
theValue = dr[i - 1].ToString();
xlWorkSheet.Cells[rowCount, i].value = theValue;
}
rowCount += 1;
}
} catch(Exception) {
throw;
}
In the stored procedure, when I populate the Datatable, I tried to explicitly specify the type with the help of the DATETIMEfollowing:
SELECT
"Date" = CONVERT(DATE,b.[Date])
...
, Excel ?
Edit
() :
int rowCount = 2;
string theValue;
DateTime dtm;
DateTime d;
try {
foreach(DataRowView dr in dv) {
for(int i = 1; i < NumColumns + 1; i++) {
switch(dr[i - 1].GetType().ToString()) {
case "System.DateTime":
dtm = Convert.ToDateTime(dr[i - 1]);
xlWorkSheet.Cells[rowCount, i].value = dtm.ToOADate();
break;
case "System.Date":
d = Convert.ToDateTime(dr[i - 1]);
xlWorkSheet.Cells[rowCount, i].value = d.ToOADate();
break;
default:
theValue = dr[i - 1].ToString();
xlWorkSheet.Cells[rowCount, i].value = theValue;
break;
}
}
rowCount += 1;
}
} catch(Exception) {
throw;
}