使用Open XML将date添加到Excel

我想用Open XML插入Date值到excel文件。

这是我的代码示例。

cell.CellValue = new CellValue(value.ToString()); cell.DataType = new EnumValue<CellValues>(CellValues.Date); 

显然,数据types应该省略!

我有同样的概率,但只是设置CellValue做了诡计!

 cell.CellValue = new CellValue(value.ToOADate().ToString()) 

我得到了答案,并与大家分享…

就像我们一样添加单元格

  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; 

我在这里用过

 cell.StyleIndex=5; 

这是在Excel中按date默认样式索引。 所以不需要添加所有的外部样式表

请享用 :)

以下为我们工作:

 c.CellValue = new CellValue(datetimeValue).ToOADate().ToString()); c.DataType = CellValues.Number; c.StyleIndex = StyleDate; 

将DataType设置为CellValues.Number,然后确保使用CellFormats中适当的样式索引来格式化单元格。 在我们的例子中,我们在工作表中创build一个样式表,StyleDate是样式表中CellFormats的一个索引。