When generating an Excel XML workbook with ASP.NET i’m appending 3 cells in a row like:
sb.Append(String.Format(
"<Cell><Data ss:Type=\"DateTime\">{1}</Data></Cell>{0}",
Environment.NewLine,
item.DateAvailable.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK")
)); // newlines added for readability;
item.DateAvailable is a C# DateTime that has to end in Excel as An cell-DateTime.
so
value from debug in VS2010 in asssembly:
2011-08-15T01:16:06.8470000
value in excel:
40761,2299142361
after manual conversion of the cell formatting:
6-08-11 5:31
However, when converting it outputs in excel as a number, and the cell formatting is set to custom. When I manually change the cell formatting back to DateTime the correct??? date is shown in the correct format. But of course, the business would not accept such a raw data they have to convert themselves 😉
Perhaps I am using the wrong StringFormat?
What is the correct format to write a DateTime in this case and output it in Excel in the correct DateTime Format?
Yes, you are using a “wrong” string format, i.e. a format that Excel does not automatically recognize (or parse appropriately) as a date. Drop the
T. Also, the date-time format in Excel rounds at least to milliseconds, if not to integer seconds, so you might as well drop some of those decimal places.This should work: