【问题标题】:EPPlus ignoring fractional seconds?EPPlus 忽略小数秒?
【发布时间】:2018-09-17 19:34:15
【问题描述】:

使用 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;仍然会产生上述错误的日期时间格式。

【问题讨论】:

  • 解决办法是"yyyy-MM-dd HH:mm:ss.000",
  • 如果我的解决方案有效?
  • 结果:2018-06-18 15:45:25.000
  • 它对我有用。您确定 cellValue 包含毫秒吗?我的代码中唯一的区别是,我在分配值之前设置了格式。
  • 我找错地方了。在 cellValue 中传递的值是调用 DateTime.TryParse() 产生的 DateTime 变量。文档中没有这样说,但该功能会切断毫秒。

标签: c# datetime epplus


【解决方案1】:

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

    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;
    }

【讨论】:

  • 我感谢您的回答,即使这不是,因为您的问题“您确定 cellValue 包含毫秒?”最终让我发现我调用了一个函数,它在没有意识到的情况下切断了毫秒(见上文)。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-13
相关资源
最近更新 更多