0

我正在使用 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);
            }

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

4

1 回答 1

2

您必须手动设置这些值。

您可以编写一个 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);
于 2012-11-13T14:05:00.947 回答