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

Mapper.Put<T> overload method have bug, ForHeader method will never execute !!! #22

Closed VAllens closed 6 years ago

VAllens commented 6 years ago

The firstRow variable does not get the object returned by the PopulateFirstRow method

private void Put<T>(ISheet sheet, IEnumerable<T> objects, bool overwrite)
{
    var sheetName = sheet.SheetName;
    var firstRow = sheet.GetRow(sheet.FirstRowNum);
    var objectArray = objects as T[] ?? objects.ToArray();
    var type = MapHelper.GetConcreteType(objectArray);

    var columns = GetTrackedColumns(sheetName, type) ??
                   GetColumns(firstRow ?? PopulateFirstRow(sheet, null, type), type);

    if (firstRow == null)
    {
        PopulateFirstRow(sheet, columns, type);
    }

    // Injects custom action for headers.
    if (overwrite && HasHeader && _headerAction != null)
    {
        firstRow?.Cells.ForEach(c => _headerAction(c));
    }

    var rowIndex = overwrite
        ? HasHeader ? sheet.FirstRowNum + 1 : sheet.FirstRowNum
        : sheet.GetRow(sheet.LastRowNum) != null ? sheet.LastRowNum + 1 : sheet.LastRowNum;

    MapHelper.EnsureDefaultFormats(columns, TypeFormats);

    foreach (var o in objectArray)
    {
        var row = sheet.GetRow(rowIndex);

        if (overwrite && row != null)
        {
            sheet.RemoveRow(row);
            row = sheet.CreateRow(rowIndex);
        }

        row = row ?? sheet.CreateRow(rowIndex);

        foreach (var column in columns)
        {
            var pi = column.Attribute.Property;
            var value = pi?.GetValue(o);
            var cell = row.GetCell(column.Attribute.Index, MissingCellPolicy.CREATE_NULL_AS_BLANK);

            column.CurrentValue = value;
            if (column.Attribute.TryPut == null || column.Attribute.TryPut(column, o))
            {
                SetCell(cell, column.CurrentValue, column, setStyle: overwrite);
            }
        }

        rowIndex++;
    }

    // Remove not used rows if any.
    while (overwrite && rowIndex <= sheet.LastRowNum)
    {
        var row = sheet.GetRow(rowIndex);
        if (row != null) sheet.RemoveRow(row);
        rowIndex++;
    }
}

error:

if (firstRow == null)
{
    PopulateFirstRow(sheet, columns, type);
}

right:

if (firstRow == null)
{
    firstRow = PopulateFirstRow(sheet, columns, type);
}