How to insert a date to an Open XML worksheet?

后端 未结 7 1226
渐次进展
渐次进展 2021-02-12 10:42

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 = Cell

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-12 11:35

    You have to convert DateTime to double using function ToOADate i.e.:

    DateTime dtValue = DateTime.Now;
    string strValue = dtValue.ToOADate().ToString(CultureInfo.InvariantCulture);
    

    then set it as CellValue

    Cell cell;
    cell.DataType = new EnumValue(CellValues.Date);
    cell.CellValue = new CellValue(strValue);
    

    Remember to format cell using DateTime formatting, otherwise you will see double value, not date.

提交回复
热议问题