问题
I would like to insert Date value to excel file using Open XML.
Here is my code sample.
cell.CellValue = new CellValue(value.ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.Date);
回答1:
Apparently, the DataType should be omitted!
I was having the same prob, but just setting the CellValue did the trick!
cell.CellValue = new CellValue(value.ToOADate().ToString())
回答2:
I got the answer and sharing with you all...
Just add cell as we do..
Cell cell =new Cell(){ cellReference=A1 }; //Or other necessary details
//Add value to cell in Double Format then convert it into string using ToString()
cell.cellValue = new CellValue(DateTime.Now().ToDouble().ToString());
//Set the data type as Number
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
//Give its StyleIndex = 5 (default style index of date)
cell.StyleIndex=5;
Here I have used
cell.StyleIndex=5;
which is By Default Style Index of date in Excel. So no need to add all the external styylesheets
Enjoy :)
回答3:
The following worked for us:
c.CellValue = new CellValue(datetimeValue).ToOADate().ToString());
c.DataType = CellValues.Number;
c.StyleIndex = StyleDate;
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.
来源:https://stackoverflow.com/questions/2709171/adding-date-to-excel-using-open-xml