How to insert a date to an Open XML worksheet?

后端 未结 7 1237
渐次进展
渐次进展 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:48

    I used the code provided by Andrew J, but the DataType CellValues.Date produced a corrupted xlsx-file for me.

    The DataType CellValues.Number worked fine for me (Don't forget to set NumberFormatId):

    cell.DataType = new EnumValue<CellValues>(CellValues.Number);
    

    My whole code:

    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; //StyleIndex of CellFormat cfBaseDate -> See below
    cell.Append(cellValue);
    

    My CellFormat for this cell in the Stylesheet looks like:

    CellFormat cfBaseDate = new CellFormat() { 
     ApplyNumberFormat = true,
     NumberFormatId = 14, //14 is a localized short Date (d/m/yyyy) -> See list below
     //Some further styling parameters
    }; 
    

    If you'd like to format your date another way, here is a list of all default Excel NumberFormatId's

    ID  FORMAT CODE
    0   General
    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 ;[Red](#,##0)
    39  #,##0.00;(#,##0.00)
    40  #,##0.00;[Red](#,##0.00)
    45  mm:ss
    46  [h]:mm:ss
    47  mmss.0
    48  ##0.0E+0
    49  @
    

    Source of list: https://github.com/ClosedXML/ClosedXML/wiki/NumberFormatId-Lookup-Table

    I know this list is from ClosedXML, but it's the same in OpenXML.

    0 讨论(0)
提交回复
热议问题