请注意,CellValues.Date 枚举成员仅
在 Microsoft Office 2010 及更高版本中可用(请参阅MSDN library
了解更多信息)。
因此,如果您使用 Microsoft Office 2007 打开一个包含 CellValues.Date 类型单元格的 Excel 电子表格
你会得到一个错误。
此外,CellValues.Date 类型的单元格的值必须是
采用 ISO 8601 格式(请参阅 Office Open XML 第 1 部分规范,第 18.17.4.1 节)。
总结 ISO 8601 格式:
- ISO 8601 中的日期以以下格式表示:
YYYY-MM-DD。
- 时间以下列格式存储:
hh:mm:ss。
- 日期和时间使用大写字母 T 分隔:
YYYY-MM-DDThh:mm:ss。
更多信息请参考以下文章 (WIKIPEDIA)
在 ISO 8601 格式上。
以下代码示例显示了 CellValues.Date 类型单元格的创建:
Protected Shared Function CreateCell(columnIndex As Integer, rowIndex As Integer, value As DateTime, styleIndex As Integer) As Cell
Dim cell As Cell = New Cell()
cell.DataType = CellValues.Date
Dim v As CellValue = New CellValue()
v.Text = value.ToString("yyyy-MM-ddThh:mm:ss") ' Use ISO 8601 format for date value
cell.CellReference = "" ' Set cell reference here! E.g. A1
cell.CellValue = v
cell.StyleIndex = styleIndex
Return cell
End Function
Protected Function CreateNumberingFormatForDateCells() As NumberingFormat
Dim numberingFormat As NumberingFormat = New NumberingFormat()
numberingFormat.NumberFormatId = CType(165U, UInt32Value)
numberingFormat.FormatCode = "dd-mm-yyyy"
return numberingFormat
End Function
Protected Function CreateCellFormatForDateCells() As CellFormat
Dim cellFormat As CellFormat = New CellFormat()
cellFormat.NumberFormatId = CType(165U, UInt32Value)
cellFormat.ApplyNumberFormat = true
return cellFormat
End Function
Sub Main()
' ... Code to get/create your workbook
Dim workbookPart As WorkbookPart ...
' Add number format and cell style for date cells.
Dim nf As NumberingFormats = New NumberingFormats()
workbookPart.WorkbookStylesPart.Stylesheet.NumberingFormats = nf
workbookPart.WorkbookStylesPart.Stylesheet.NumberingFormats.Append(CreateNumberingFormatForDateCells());
workbookPart.WorkbookStylesPart.Stylesheet.CellFormats.Append(CreateCellFormatForDateCells());
' Call CreateCell() to create date cells
Dim c As Cell = CreateCell(0,0,DateTime.Now, workbookPart.WorkbookStylesPart.Stylesheet.CellFormats.Count())
' Code to append cell to spreadsheet
End Sub
请注意,通过将单元格类型设置为CellValues.Date,我们仅指定日期值存储在
ISO 8601 格式。我们仍然需要为日期指定一个显示单元格样式。
在上面的示例中,我按顺序创建了一个单元格样式(并设置了单元格样式索引)
告诉excel如何显示日期值。