使用Apache Poi从Excel创建对象

时间:2019-07-15 06:38:22

标签: java excel apache-poi

我正在尝试从Excel创建对象。 Excel文件看起来像这样 enter image description here

我正在尝试根据本帖子How to convert my xlsx sheet to java object using Apache POI的想法。第一个答案看起来不错。但是,我对如何创建对象的了解很少。

public class Tr {

    String empName;
    String empID;
    String empDept;

    //Constructor
    public Tr(String empName, String empID, String empDept) {
        this.empName = empName;
        this.empID = empID;
        this.empDept = empDept;
    }

    //The following part will  read Excel and return cell data
    public static ArrayList<String> name = new ArrayList<String>();
    public static ArrayList<String> deptId = new ArrayList<String>();
    public static ArrayList<String> dName = new ArrayList<String>();

    public ArrayList<String> getCellData(int cellNo) throws IOException {

        FileInputStream file = new FileInputStream("C:\\MyTemp\\People.xlsx");
        HSSFWorkbook book = new HSSFWorkbook(file);
        HSSFSheet sheet = book.getSheet("Sheet1");
        Iterator<Row> it = sheet.iterator();

        ArrayList<String> cellData = new ArrayList<String>();
        while (it.hasNext()) {
            cellData.add(it.next().getCell(cellNo).getStringCellValue());
        }
        return cellData;
    }

    //Assigning cell data to variables and converting to string 
    public void assignEmployee() throws IOException {
        empName = getCellData(0).toString();
        empID = getCellData(1).toString();
        empDept = getCellData(2).toString();
    }

    public static void main(String[] args) {

    }
}

您的帮助或想法将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

您链接的答案并不完全是这种方式。该答案建议您应该一次加载excel文件,然后迭代每个jWK以便将其分配给jWK实例。

因此基本用法如下:

Row

换句话说,类Employee看起来像这样:

    FileInputStream file = new FileInputStream("C:\\MyTemp\\People.xlsx");
    HSSFWorkbook book = new HSSFWorkbook(file);
    HSSFSheet sheet = book.getSheet("Sheet1");

    Iterator<Row> it = sheet.iterator();
    Employee emp = new Employee();
    while(itr.hasNext()){
        Row row = itr.next();
        emp.assignEmployee(row);
        //  use emp instance here
    }

在这里,您可以根据需要使用Employee实例。我个人将更进一步,并在public class Employee{ private String empNo; private String empName; public void assignEmployee(Row row) { empNo = row.getCell(0).toString(); empName = row.getCell(1).toString(); } } 的构造函数中进行分配,而不要使用名为Employee的方法(这样可能会导致线程问题)。

Employee