读取多个excel文件并将数据推送到java中的相应对象,寻找有效的方法

时间:2015-03-13 17:05:29

标签: java excel apache-poi

我有多个excel文件,使用apache poi库我可以读取每个excel文件并将数据设置为object。

例如,employee.xls:

emp.id   firstname  dob
111111   fName      19/10/2011
222222   tName      11/12/2010

和对象如下:

 class Employee {
    private String empId;
    private String firstname;
    private Date dob;
    public String getEmpId() {
        return empId;
    }
    public void setEmpId(String empId) {
        this.empId = empId;
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public Date getDob() {
        return dob;
    }
    public void setDob(Date dob) {
        this.dob = dob;
    }
}

对于推送数据,我需要从excel文件中读取并设置为Employee对象。如果我有超过20个不同的xls文件,那么我需要为每个excel文件编写代码来读取,然后将数据设置为相应的对象。有没有其他有效的方法来实现这一目标?

提前致谢!

1 个答案:

答案 0 :(得分:1)

假设结构总是相同的,似乎逻辑很简单:

  1. 跳过第一行
  2. 每行
    • 创建对象的实例
    • 填充字段。
  3. 我建议读者这样:

    public class SheetReader<T> {
        private final Supplier<T> supplier; 
        private final List<BiConsumer<Cell, T>> populators;
    
    
        public SheetReader(Supplier<T> supplier, List<BiConsumer<Cell, T>> populators) {
            this.supplier = supplier;
            this.populators = populators;
        }
    
    
        public List<T> readSheet(final Sheet sheet, final boolean hasHeader) {
            final Iterator<Row> rows = sheet.iterator();
            if(hasHeader) {
                //skip first row
                rows.next();
            }
            final List<T> ts = new LinkedList<>();
            while(rows.hasNext()) {
                final Row row = rows.next();
                final T t = supplier.get();
                for(int i =0; i<populators.size();++i) {
                    populators.get(i).accept(row.getCell(i), t);
                }
                ts.add(t);
            }
            return ts;
        }
    
    }
    

    用法如下:

    //should be ArrayList due to random access. Could also be Guava ImmutableList
    final List<BiConsumer<Cell, Employee>> populators = new ArrayList<>();
    //add the populators in order
    populators.add((c, e) -> e.setEmpId(c.getStringCellValue()));
    populators.add((c, e) -> e.setFirstname(c.getStringCellValue()));
    populators.add((c, e) -> e.setDob(c.getDateCellValue()));
    //pass constructor as producer
    final SheetReader<Employee> reader = new SheetReader<>(Employee::new, populators);
    //can read many sheets of same type with same reader
    final List<Employee> employees = reader.readSheet(sheet, true);