I'm using Microsoft Open XML SDK 2 and I'm having a really hard time inserting a date into a cell. I can insert numbers without a problem by setting Cell.DataType = CellValues.Number
, but when I do the same with a date (Cell.DataType = CellValues.Date
) Excel 2010 crashes (2007 too).
I tried setting the Cell.Text
value to many date formats as well as Excel's date/numeric format to no avail. I also tried to use styles, removing the type attribute, plus many other pizzas I threw at the wall…
Can anyone point me to an example inserting a date to a worksheet?
I used the code provided by Andrew J, but the
DataType
CellValues.Date
produced a corrupted xlsx-file for me.The
DataType
CellValues.Number
worked fine for me (Don't forget to setNumberFormatId
):My whole code:
My CellFormat for this cell in the Stylesheet looks like:
If you'd like to format your date another way, here is a list of all default Excel
NumberFormatId
'sSource of list: https://github.com/ClosedXML/ClosedXML/wiki/NumberFormatId-Lookup-Table
I know this list is from ClosedXML, but it's the same in OpenXML.
You have to convert
DateTime
todouble
using functionToOADate
i.e.:then set it as
CellValue
Remember to format cell using
DateTime
formatting, otherwise you will seedouble
value, not date.The following worked for us:
Set the DataType to CellValues.Number and then be sure to format the cell with the appropriate style index from the CellFormats. In our case we build a stylesheet within the worksheet, and StyleDate is an index into the CellFormats in the stylesheet.
Use Shared String:
Then later in code:
a) Get compatibility with Excel 2007, Excel 2007 Viewer etc. b) DateTime before 1.1.1900 write as string.
There are 2 ways to store dates in OpenXml; by writing a number (using
ToOADate
) and setting theDataType
toNumber
or by writing an ISO 8601 formatted date and setting theDataType
toDate
. Note that the defaultDataType
isNumber
so if you go with the first option you don't have to set theDataType
.Whichever method you choose, you'll need to set the style as Excel displays both methods identically. The following code shows an example of writing a date using the
Number
format (with and without explicitly setting theDataType
) and using the ISO 8601 format.