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.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Problems importing sheet with date as double

akordowski opened this issue · comments

I'm trying to import a Excel sheet which contains several columns which can have date values as double. Here is my approach:

var mapper = new Mapper(filePath);
mapper.TrackObjects = false;
mapper.Map<Model>(0, o => o.Property1);
mapper.Map<Model>(1, o => o.Property2);
...
mapper.Map(column =>
{
    if (column.Attribute.Index == 10 && column.CurrentValue is double value)
    {
        column.CurrentValue = DateTime.FromOADate(value);
    }
    
    return true;
});

var result = mapper.Take<Model>().ToList();

When debugging, the debugger dont even stop in the mapper.Map(column => ...) method.

All I got as a result is a list of errors for the specific columns:
"Object reference not set to an instance of an object."

How do I have configure the mapper to convert the double to date?
Any help is welcomed!

There is a built-in conversion from double to DateTime (with DateTime.FromOADate(value)), you don't have to do anything.

Two more things for your code.

  1. Please use another overload for custom resolver when you explicitly map a property.
    Specify the resolver together with the column mapping. What you did is just to specify default resolvers for those columns are not explicitly mapped.
  2. When it comes to custom resolver, the column.CurrentValue is already in type of DateTime, it was converted by the mapped target property type.
mapper.Map<Model>(
    0,
    o => o.Property1,
    (column, target) =>
    {
        if (column.CurrentValue is double value1){/* never true */}
        if (column.CurrentValue is DateTime value2){/* always true */}
        return true;
    });