How to insert a date to an Open XML worksheet?

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

    a) Get compatibility with Excel 2007, Excel 2007 Viewer etc. b) DateTime before 1.1.1900 write as string.

    DateTime dat = (DateTime)dr[dc.ColumnName];
    
    //Not working with Excel 2007
    //cell.DataType = CellValues.Date;
    //cell.CellValue = new CellValue(dat.ToString("s"));
    
    double diff = (dat - new DateTime(1899, 12, 30)).TotalSeconds / 86400.0;
    if (diff > 1)
    {
        cell.DataType = CellValues.Number;
        cell.CellValue = new CellValue(diff.ToString().Replace(",", "."));
    
        if (dat.TimeOfDay == new TimeSpan(0))
        {                                
            cell.StyleIndex = 2;   //Custom Style NumberFormatId = 14 ( d/m/yyyy)
        }
        else
        {
            cell.StyleIndex = 1;   //Custom Style NumberFormatId = 22 (m/d/yyyy H:mm)
        }
    }
    else
    {
        cell.DataType = CellValues.String;
        cell.CellValue = new CellValue(dat.ToString());
    }
    

提交回复
热议问题