0

我想将 excel 行的当前行号添加到映射的 Employee 变量中。

从下面的示例中:我想知道员工“Yuri”在 excel 行号 8 中。

但我找不到任何访问它的方法。XLSRowCursor 有它,但我怎样才能将它添加到映射的 bean 中?我知道读者在编写异常时使用当前处理的行号,POI 也有。

我这边一个简单的自我行计数解决方案不是一个有效的想法,因为我们在错误机制中使用了跳过行。

任何提示或提示?

xml文件:

 <?xml version="1.0" encoding="ISO-8859-1"?>
   <workbook>
     ....
    <loop startRow="7" endRow="7" items="department.staff" var="employee" varType="net.sf.jxls.reader.sample.Employee">
      <section startRow="7" endRow="7">
       <mapping row="7" col="0">employee.name</mapping>
       <mapping row="7" col="1">employee.age</mapping>
       <mapping row="7" col="3">employee.payment</mapping>
       <mapping row="7" col="4">employee.bonus</mapping>
     </section>
  ...
 </loop>
 </worksheet>
</workbook>

excel文件:员工

6 Name  Age Birth Date  Payment Bonus   Total   Superior Name
7 Oleg  32  2-Jan-74    2000    20,00%  2400    Maxim
8 Yuri  29  26-Sep-77   1800    15,00%  2070    Oleg
9 Leonid    30  12-Feb-76   1700    20,00%  2040    Oleg
10 Alex 28  18-Aug-78   1600    20,00%  1920    Oleg
11 Employee Payment Totals:         7100        8430    
4

2 回答 2

1

您可以扩展SimpleBlockReaderImpl并覆盖其read(XLSRowCursor cursor, Map beans)方法以使用XLSRowCursor获取当前 Excel 行并将其注入 bean。

目前没有自动方法通过 XML 注入您自己的 CustomBlockReader 实现,因此您必须通过从XLSReader获取所有工作表阅读器并用您的自定义实例替换内部块阅读器来手动完成。

于 2016-02-08T13:03:03.260 回答
0

我有同样的问题,但通过一个技巧解决了:使用在每次解析之前自动初始化的静态变量将行号存储在 bean 的附加属性中

bean 将具有一个附加属性“rowNumber”,其中包含 Excel 文件中的行号,以及一个静态变量“position”,该变量将在每个对象实例化时递增(这意味着在 Excel 文件中处理新行)

package com.test.parser.model;

public class Employee{

    private String name;
    private String age;
    private String payment;

    private static int position = 2;

    private int rowNumber;

    public Employee(){
        setRowNumber(position++);
    }

    public static void resetRowNumber() {
        position = 2;
    }

    public int getRowNumber() {
        return rowNumber;
    }

    public void setRowNumber(int rowNumber) {
        this.rowNumber = rowNumber;
    }
}

在读取 JXLS 之前,通过静态方法 Employee.resetRowNumber() 将静态值重置为起始行(在我的情况下为第二行),如下所示:

XLSReader mainReader = ReaderBuilder.buildFromXML(<InputStream of XML Mapping File>);
List<Employee> employeeList = new ArrayList<Employee>();
Employee.resetRowNumber();
beans.put("department.staff", employeeList);
mainReader.read(inputXLS, beans);

在解析结束时,我们将能够通过Employee.getRowNumber().

于 2019-08-20T10:38:11.823 回答