Using EPPlus to write the contents of a datagrid to an Excel file. This function:
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);
}
}
If the format string is set to "yyyy-MM-dd HH:mm:ss.ff", then the dates in the Excel file look like this: 2018-06-18 15:45:25.ff
If the format string is set to "yyyy-MM-dd HH:mm:ss.00", then the dates in the Excel file look like this: 2018-06-18 15:45:25.00
Is EPPlus removing the fraction of a second (I know it's there because I can see it in the datagrid), or is it mangling the format string somehow? Is this a bug? Is there a workaround?
Thanks.
Update: updated EPPlus from 4.1.0.1 to 4.5.2.1 and added OpenXML which wasn't previously needed; still produces wrong datetime formats as above.
Here how I do it in my code. This is a Extension method.
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;
}