EPPlus日期单元格数据类型不起作用

时间:2014-05-22 20:00:11

标签: c# excel epplus

我有一些代码接受IEnumerable并从中生成Excel文档。 IEnumerable中的对象有一个日期字段,我希望这些对象在Excel中被格式化为日期。但是,当您在Excel中查看它时,日期似乎不是“日期”数据类型,直到您双击单元格,然后按Enter键。执行此操作时,值将移至右对齐,表过滤器可正常工作。如果您没有双击并输入事物,则该值左对齐,表格过滤器将其视为文本而不是日期。我需要Excel将其视为开箱即用的日期。

这是我的代码。

/// <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中的单元格并转到格式化单元格时,它会显示已选择日期,但它似乎不适用于表格过滤器。而不是“从最旧到最新排序”,我得到“从a到z排序”。

1 个答案:

答案 0 :(得分:9)

不要使用ToString(),

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

它无法确定DataFormat是什么。 我有一个十进制数字的类似问题,我试图&#34;预先格式化&#34;它们。

同样在您的第一个&#39; if&#39;中,您检查该值是否为日期,是否应将返回的值放入Excel工作表中,而不是放入名为dt的新变量?

相关问题