Adding Date to Excel using Open XML [closed]

别来无恙 提交于 2019-12-10 17:17:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!