C# EPPlus忽略分数秒?
使用EPPlus将datagrid的内容写入Excel文件。此功能:C# EPPlus忽略分数秒?,c#,datetime,epplus,C#,Datetime,Epplus,使用EPPlus将datagrid的内容写入Excel文件。此功能: public static void FormatExcelCell(OfficeOpenXml.ExcelRange cellExcel, object cellValue, System.Type cellValueType,
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是在删除一秒钟的小数点(我知道它在那里,因为我可以在datagrid中看到它),还是在以某种方式破坏格式字符串?这是虫子吗?有解决办法吗
谢谢
更新:将EPPlus从4.1.0.1更新到4.5.2.1,并添加了以前不需要的OpenXML;仍然会产生如上所述的错误日期时间格式。这里是我如何在代码中实现它的。这是一种扩展方法
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;
}
解决方案是“yyyy-MM-dd HH:MM:ss.000”,如果我的解决方案有效?结果:2018-06-18 15:45:25.000它对我有效。您确定cellValue包含毫秒吗?代码中唯一的区别是,我在赋值之前设置了格式。我找错了地方。cellValue中传递的值是调用DateTime.TryParse()产生的DateTime变量。文档中没有这样说,但该函数会减少毫秒数。尽管答案不是这样,但我还是要感谢你的回答,因为你的问题“你确定cellValue包含毫秒数吗?”最终让我发现我调用了一个函数,该函数在没有意识到的情况下减少了毫秒数(见上文)。谢谢