donnytian / Npoi.Mapper

Use this tool to import or export data with Excel file. The tool is a convention based mapper between strong typed object and Excel data via NPOI.
MIT License
601 stars 115 forks source link

Is there a way to set the format for all DateTime types? #4

Closed cda-1 closed 7 years ago

cda-1 commented 7 years ago

Without setting a format on DateTime properties, excel seems to format them as integers. For example, 10/26/2016 prints as 42669.

I see that I can easily format a DateTime property if I know it in advance, like this: mapper.Format<MyObject>("yyyy-MM-dd", x => x.MyDateField)

I tried to make it generic, so I don't need a custom method for every one of my types:

foreach (var property in typeof(T).GetProperties())
{
    if (property.PropertyType == typeof(DateTime) ||
        property.PropertyType == typeof(DateTime?))
    {
        mapper.Format<T>("yyyy-MM-dd", x => property.GetValue(x));
    }
}

But this fails with "Unable to cast object of type 'System.Linq.Expressions.InstanceMethodCallExpressionN' to type 'System.Linq.Expressions.UnaryExpression'."

Would you help me figure this out, or consider building in a default format for DateTime that isn't an integer?

donnytian commented 7 years ago

@cda-1 new method added, try like below: mapper.UseFormat(typeof(DateTime), "yyyy.MM.dd hh.mm.ss");