读取excel文件并添加到java实体类中

我正在阅读使用jxl库的excel文件。但是当我想将单元格内容添加到pojo类属性中时,我正面临一个问题。 这样我有Employee类;

public class Employee { private String id; private String name; private String email; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } public static void read(String path) throws IOException { File inputWorkbook = new File(path); Workbook w; String[] excel_data = new String[3]; try { w = Workbook.getWorkbook(inputWorkbook); // Get the first sheet Sheet sheet = w.getSheet(0); // Loop over first 10 column and lines Vector<Employee> data = new Vector<Employee>(); for (int j = 1; j < sheet.getRows(); j++) { Employee emp = new Employee() for (int i = 0; i < sheet.getColumns(); i++) { Cell cell = sheet.getCell(i, j); // d.add(cell.getContents()); emp.setId(cell.getContents()); emp.setName(cell.getContents()); emp.setEmail(cell.getContents()); } // d.add("\n"); data.add(emp); //insertEmployee(emp); } 

这里我的代码我可以添加单元格内容到vector对象。 但我想设置单元格内容值到Employee类属性。请告诉我如何实现this.I没有从emp对象得到正确的值。当我向列表中添加内容时,我在代码中做错了什么

您将不得不手动设置值。

您可以编写一个switch语句并为每个列索引设置如下所示的值:

 List<Employee> employees = new ArrayList<Employee>(); ... Employee emp = new Employee(); for (int i = 0; i < sheet.getColumns(); i++) { Cell cell = sheet.getCell(i, j); switch (i) { // column 0 = ID case 0: emp.setId(cell.getContents()); break; // column 1 = Name case 1: emp.setName(cell.getContents()); break; // column 2 = Email case 2: //... etc break; } } employees.add(emp);