NPOI Mapper可以设置行号吗

Can NPOI Mapper set the row number

我目前正在使用 c# 中的 npoi.mapper 将 excel 文件读入 poco classes 以进行进一步处理,并且一切正常。

系统已经发展壮大,多个电子表格经常并行处理因此我想在我的 poco class 中包含文件名和行号以用于调试目的。

到目前为止,我只是在 for 循环中手动添加了文件名和行号,但想知道我是否可以通过让 npoi.mapper 为我执行此操作来重构和清理我的代码?

这是我的代码:

   var mapper = new Mapper(excelStream);
   var rows = mapper.Take<MyPocoClass>("Sheet2");

   for(int i = 0; i < rows.Length; i++)
   {
       var row = rows[i];

       row.Filename = excelName;
       row.RowNumber = i;
   } 

我已经阅读了 GitHub Page 上的文档,听起来我应该使用自定义解析器,但我看不出如何访问其中的行号?

我看了一下 Mapper.cs on github and I realized that the RowInfo and IRowInfo classes(包含行号)仅用于 public 方法的 returns。

在扩展文件夹中,我在 class EnumerableExtensions 处找到了一个名为 ForEach<T>IEnumerable<T> ExtensionMethod,它可以用作您当前代码的替代方法。

这是一个未经测试的解决方案。

   var mapper = new Mapper(excelStream);
   var rows = mapper.Take<MyPocoClass>("Sheet2");

   rows.Foreach<RowInfo<MyPocoClass>>(row => {
        row.Value.Filename = "Sheet2";
        row.Value.RowNumber = row.RowNumber;
   });

这只是您当前代码的一个合成糖。


在我看来,完成此类工作的最佳方法是执行以下步骤:

1) 创建包含属性 FilenameRowNumber 的接口或基类型。基本类型示例:

public class MyPocoFromExcelBase 
{
    public string FileName { get; set; }

    public int RowNumber { get; set; }
}

2) 在您的 MyPocoClass 和代表 excel 文件中的行的任何其他 class 上继承 MyPocoFromExcelBase

3) 为 IEnumerable<RowInfo<MyPocoFromExcelBase>> 创建扩展方法并进行映射:

    public static void MapRowNumber(this IEnumerable<RowInfo<MyPocoFromExcelBase>> sequence, string fileName)
    {
        if (sequence == null) return;

        foreach (var item in sequence)
        {
            item.Value.Filename = fileName;
            item.Value.RowNumber = item.RowNumber;
        }
    }

4) 然后你可以在任何映射器中做这样的事情:

var mapper = new Mapper(excelStream);
var rows = mapper.Take<MyPocoClass>("Sheet2");
rows.MapRowNumber("Sheet2");

这样你就不需要在整个代码中重写这个逻辑。