EPPlusdate单元格数据types不起作用

我有一些接受IEnumerable并从中生成Excel文档的代码。 IEnumerable中的对象有一个date字段,我希望这些在Excel中被格式化为date。 但是,在Excel中查看时,date似乎不是“date”数据types,除非您在单元格中双击,然后按Enter键。 当你这样做,值移动到右alignment,表格filter正常工作。 如果你不做双击并input东西,那么值是左alignment的,表格filter把它当作文本而不是date。 我需要Excel把它当作一个开箱即用的date。

这是我的代码。

/// <summary> /// Converts any IEnumerable to an Excel Document. Objects appear in the order declared in the class. /// </summary> /// <typeparam name="T">Any object.</typeparam> /// <param name="objects">List of objects to generate document from.</param> /// <returns>Byte array representing a .xlsx file.</returns> public static byte[] ToExcelDocument<T>(this IEnumerable<T> objects) { int currentrow = 1; Type type = typeof(T); List<PropertyInfo> propertyinfos = type.GetProperties().ToList(); int numcolumns = propertyinfos.Count; ExcelPackage pck = new ExcelPackage(); ExcelWorksheet ws = pck.Workbook.Worksheets.Add(type.Name + "(s)"); for (int i = 0; i < numcolumns; i++) { ws.Cells[currentrow, i + 1].Value = propertyinfos[i].Name; } currentrow++; foreach (object o in objects) { for (int i = 0; i < propertyinfos.Count; i++) { if (o.GetType().GetProperty(propertyinfos[i].Name).PropertyType == typeof(DateTime)) { ws.Cells[currentrow, i + 1].Style.Numberformat.Format = "m/d/yyyy"; DateTime dt = (DateTime)(o.GetType().GetProperty(propertyinfos[i].Name).GetValue(o, null)); } else if (o.GetType().GetProperty(propertyinfos[i].Name).PropertyType == typeof(DateTime?)) { DateTime? dt = (DateTime?)(o.GetType().GetProperty(propertyinfos[i].Name).GetValue(o, null)); if (dt.HasValue) { ws.Cells[currentrow, i + 1].Style.Numberformat.Format = "m/d/yyyy"; ws.Cells[currentrow, i + 1].Value = dt.Value.ToString("MM/dd/yyyy"); } } else { ws.Cells[currentrow, i + 1].Value = o.GetType().GetProperty(propertyinfos[i].Name).GetValue(o, null); } } currentrow++; } ExcelAddressBase eab = new ExcelAddressBase(1, 1, currentrow - 1, numcolumns); ws.Tables.Add(eab, "MyTable"); ws.Tables["MyTable"].TableStyle = OfficeOpenXml.Table.TableStyles.Medium15; ws.Cells.AutoFitColumns(); MemoryStream ms = new MemoryStream(); pck.SaveAs(ms); return ms.ToArray(); } 

我会认为ws.Cells[currentrow, i + 1].Style.Numberformat.Format = "m/d/yyyy"; 足以完成我想要的,但似乎没有工作。 当您右键单击Excel中的单元格并转到格式单元格时,它会显示date已被选中,但它似乎不适用于表格filter。 而不是“sorting最旧到最新”,我得到“sorting从一个到z”。

不要使用ToString(),

 ws.Cells[currentrow, i + 1].Value = dt.Value; // dont do this -> .ToString("MM/dd/yyyy"); 

它不能确定DataFormat是什么。 我有一个十进制数类似的问题,我试图“预格式化”他们。

同样在你的第一个'如果',你检查的值是一个date,不应该返回的值放入Excel表,而不是一个新的variables名为dt?