我使用了Andrew J提供的代码,但是DataType
CellValues.Date
对我生成的xlsx文件损坏。
DataType
CellValues.Number
对我来说工作正常 (不要忘记设置NumberFormatId
):
cell.DataType = new EnumValue<CellValues>(CellValues.Number)
完整的代码:
DateTime valueDate = DateTime.Now;
string valueString = valueDate.ToOADate().ToString();
CellValue cellValue = new CellValue(valueString);
Cell cell = new Cell();
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
cell.StyleIndex = yourStyle;
cell.Append(cellValue);
这个单元格在样式表中的CellFormat如下:
CellFormat cfBaseDate = new CellFormat() {
ApplyNumberFormat = true,
NumberFormatId = 14,
};
如果您想以另一种方式格式化日期,这里是所有默认Excel NumberFormatId
的列表:
ID 格式码
0 常规
1 0
2 0.00
3 #,##0
4 #,##0.00
9 0%
10 0.00%
11 0.00E+00
12 # ?/?
13 # ??/??
14 d/m/yyyy
15 d-mmm-yy
16 d-mmm
17 mmm-yy
18 h:mm tt
19 h:mm:ss tt
20 H:mm
21 H:mm:ss
22 m/d/yyyy H:mm
37 #,##0 ;(#,##0)
38 #,##0 ;[红色](#,##0)
39 #,##0.00;(#,##0.00)
40 #,##0.00;[红色](#,##0.00)
45 mm:ss
46 [h]:mm:ss
47 mmss.0
48 ##0.0E+0
49 @
列表来源:https://github.com/ClosedXML/ClosedXML/wiki/NumberFormatId-Lookup-Table
我知道这个列表来自ClosedXML,但在OpenXML中也是相同的。