How to insert a date to an Open XML worksheet?

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

    When creating new SpreadsheetDocument from scratch, for Date formatting to work, minimal Stylesheet has to be created.

    Critical are those few lines:

    new CellFormat
    {
        NumberFormatId = 14,
        ApplyNumberFormat = true
    })
    

    Full Stylesheet class:

    using (var spreadSheet = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook))
    {
        // Workbook
        var workbookPart = spreadSheet.AddWorkbookPart();
        workbookPart.Workbook =
            new Workbook(new Sheets(new Sheet { Name = "Sheet1", SheetId = (UInt32Value) 1U, Id = "rId1" }));
    
        // Add minimal Stylesheet
        var stylesPart = spreadSheet.WorkbookPart.AddNewPart();
        stylesPart.Stylesheet = new Stylesheet
        {
            Fonts = new Fonts(new Font()),
            Fills = new Fills(new Fill()),
            Borders = new Borders(new Border()),
            CellStyleFormats = new CellStyleFormats(new CellFormat()),
            CellFormats =
                new CellFormats(
                    new CellFormat(),
                    new CellFormat
                    {
                        NumberFormatId = 14,
                        ApplyNumberFormat = true
                    })
        };
    
        // Continue creating `WorksheetPart`...
    

    After Stylesheet is added, DateTime can be formatted:

    if (valueType == typeof(DateTime))
    {
        DateTime date = (DateTime)value;
        cell.CellValue = new CellValue(date.ToOADate().ToString(CultureInfo.InvariantCulture));
    
        // "StyleIndex" is "1", because "NumberFormatId=14"
        // is in the 2nd item of `CellFormats` array.
        cell.StyleIndex = 1; 
    }
    

    Note that StyleIndex value depends on the order of CellFormat items in the CellFormats array or the Stylesheet object. In this example NumberFormatId = 14 item on the 2nd item in the array.

提交回复
热议问题