如何在Open XML工作表中插入日期? [英] How to insert a date to an Open XML worksheet?
问题描述
我正在使用Microsoft Open XML SDK 2,但很难将日期插入单元格中.我可以通过设置Cell.DataType = CellValues.Number
来插入数字,而不会出现问题,但是当我对日期(Cell.DataType = CellValues.Date
)执行相同操作时,Excel 2010也会崩溃(2007年也是这样).
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).
我尝试将Cell.Text
值设置为许多日期格式,而将Excel的日期/数字格式设置为无效.我还尝试使用样式,删除了type属性,以及我扔在墙上的许多其他披萨……
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?
推荐答案
您必须使用函数ToOADate
将DateTime
转换为double
,即:
You have to convert DateTime
to double
using function ToOADate
i.e.:
DateTime dtValue = DateTime.Now;
string strValue = dtValue.ToOADate().ToString(CultureInfo.InvariantCulture);
然后将其设置为CellValue
Cell cell;
cell.DataType = new EnumValue<CellValues>(CellValues.Date);
cell.CellValue = new CellValue(strValue);
请记住要使用DateTime
格式设置单元格的格式,否则您将看到double
值,而不是日期.
Remember to format cell using DateTime
formatting, otherwise you will see double
value, not date.
这篇关于如何在Open XML工作表中插入日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!