首页 > 解决方案 > EPPlus 忽略小数秒?

问题描述

使用 EPPlus 将数据网格的内容写入 Excel 文件。这个功能:

public static void FormatExcelCell(OfficeOpenXml.ExcelRange cellExcel,
                                   object cellValue, 
                                   System.Type cellValueType, 
                                   bool UseAlternateDateFormat = false)
{
    cellExcel.Value = cellValue;
    if (cellValue.ToString() != Constants.ValueForMissingTag)
    {
        if (cellValueType == typeof(System.DateTime))
            cellExcel.Style.Numberformat.Format = 
            UseAlternateDateFormat ?
            Constants.FormatDateTimeAlternateExport : 
            Constants.FormatDateTime;
    }
    else
    {
        cellExcel.Style.Fill.PatternType = 
                                    OfficeOpenXml.Style.ExcelFillStyle.Solid;
        cellExcel.Style.Fill.BackgroundColor.SetColor
                                              (Constants.ColorForMissingTag);
    }
}

如果格式字符串设置为“yyyy-MM-dd HH:mm:ss.ff”,则Excel文件中的日期如下所示:2018-06-18 15:45:25.ff

如果格式字符串设置为“yyyy-MM-dd HH:mm:ss.00”,则Excel文件中的日期如下所示:2018-06-18 15:45:25.00

EPPlus 是在删除几分之一秒(我知道它在那里,因为我可以在数据网格中看到它),还是它以某种方式破坏了格式字符串?这是一个错误吗?有解决方法吗?

谢谢。

更新:将 EPPlus 从 4.1.0.1 更新到 4.5.2.1,并添加了以前不需要的 OpenXML;仍然会产生上述错误的日期时间格式。

标签: c#datetimeepplus

解决方案


这是我在代码中的操作方式。这是一种扩展方法。

    public static void SetCellDateTimeWithMsValue(this ExcelRange cell, DateTime? value)
    {
        cell.Style.Numberformat.Format = "yyyy-MM-dd HH:mm:ss.000";
        if (!value.HasValue) return;
        cell.Value = value.Value;
    }

推荐阅读