将数据从Excel文件存储到Java Collection

我想从Excel文件中读取数据,并希望存储到Java集合,如HashMap或其他东西。

我已经通过Apache POI实现了Excel读取 – 这部分工作相当好。 现在我想知道如何将数据存储到HashMap中。

我创build了一个具有Excel数据值的POJO类。

Class EmpXcel private String emp_name; private String emp_job; // parameterised constructor // getter-setter 

现在,如果我创build这个特定的POJO类的types的HashMap。

例如。 Map<String, EmpXcel> map = new HashMap<String, EmpXcel>();

这是我从Excel读取数据的代码。

 while(itr.hasNext()){ Row nextRow = itr.next(); // For each row, iterate through all the columns Iterator<Cell> cellIterator = nextRow.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); switch (cell.getCellType()) { // if cell is numeric format case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue()+","); break; // if cell is string format case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue() + ","); break; } } System.out.println(); } 

我不知道如何将这些数据存储到types为POJO类(此处为EmpXcel)的HashMap中。

编辑:Excel表格:

 Emp_Name | Emp_Job Travis | Technical Assistant John | Professor 

另外,我想使它更通用 – 要为不同的Excel文件创build单个Java类(不考虑行数/列数)

请分享我的一些见解,以便我可以按照这种方式。

谢谢。

回答您的最新评论@inityk通过使用getColumnIndex(),您可以访问所有单元格,然后可以validation其中存在的数据。

 List<EmpXcel> empXcelList=new Arrayist<EmpXcel>(); while(itr.hasNext()){ Row nextRow = itr.next(); EmpXcel empXcelPOJO = new EmpXcel(); // For each row, iterate through all the columns Iterator<Cell> cellIterator = nextRow.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); if(cell.getColumnIndex()==0) { case Cell.CELL_TYPE_NUMERIC: System.out.print("Name should not be numeric"); break; // if cell is string format case Cell.CELL_TYPE_STRING: empXcelPOJO.setEmpName(cell.getStringCellValue()) break; }elseif(cell.getColumnIndex()==1) { case Cell.CELL_TYPE_NUMERIC: System.out.print("Name should not be numeric"); break; // if cell is string format case Cell.CELL_TYPE_STRING: empXcelPOJO.setEmpJob(cell.getStringCellValue()) break; } } empXcelList.add(empXcelPOJO); }