我有多个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 文件编写代码来读取,然后将数据设置到各自的对象。还有其他有效的方法可以实现这一目标吗?
提前致谢!
最佳答案
假设结构始终相同,逻辑似乎相当简单:
- 跳过第一行
- 对于每一行
- 创建对象的实例
- 填充字段。
我会建议读者这样:
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);
关于java - 读取多个excel文件并将数据推送到java中的各个对象,寻找有效的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29038065/