【发布时间】: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 变量。文档中没有这样说,但该功能会切断毫秒。