读取多个excel文件并将数据推送到java中的各个对象,寻找有效的方法
我有多个excel文件,使用apache poi库我可以读取每个excel文件并将数据设置为对象。
例如,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文件编写代码来读取,然后将数据设置为各自的对象。 有没有其他有效的方法来实现呢?
提前致谢!
假设结构总是相同的,逻辑似乎相当简单:
- 跳过第一行
- 为每一行
- 创build对象的一个实例
- 填充字段。
我会build议一个这样的读者:
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);