读取单个列中包含多个值的Excel文件-Java

我正在使用Apache POI阅读Excel文件。 我的Excel表格结构是这样的

|2000s| 2001, 2003, 2008, 2009| 

所以对于右边的数据,我要求它分配到2000s

直到现在我已经实现了这种方式:

 List<Class> list = new ArrayList<Class>(); File file = new File(file_path); FileInputStream fis = new FileInputStream(file); //Create an instance of workbook which refers to an excel file XSSFWorkbook wb = new XSSFWorkbook(fis); //This selects the 1st sheet XSSFSheet sheet = wb.getSheetAt(0); //Iterate through each row one by one Iterator<Row> itr = sheet.iterator(); String newName = null; String oldName = null; 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(); newName = nextRow.getCell(0).toString(); if(nextRow.getCell(1).toString().contains(",")){ StringTokenizer st = new StringTokenizer(nextRow.getCell(1).toString(),","); while(st.hasMoreTokens()){ oldName = st.nextToken(); } } else{ oldName = nextRow.getCell(1).toString(); } } System.out.println(); } 

当我编译时,它会在nextRow.getCell(1)行抛出“空指针exception”。

我不明白如何将所有逗号值映射到2000年。

这对正常数据(没有逗号)是完全正常的。

逗号值已被处理

我发布的答案,以便有人可以从这里得到帮助。

我所做的是添加String Tokenizer类,如果单元格中有逗号,则用逗号分隔符来分隔值。

让我们看看下面的代码

  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(); newName = nextRow.getCell(0).toString(); if(nextRow.getCell(1).toString().contains(",")){ StringTokenizer st = new StringTokenizer(nextRow.getCell(1).toString(),","); while(st.hasMoreTokens()){ oldName = st.nextToken(); } } else{ oldName = nextRow.getCell(1).toString(); } } System.out.println(); } 

这里newName获取第一列(2000s)的值, oldName基于','分隔符获取标记 – 在这种情况下,2001,2003,2008,2009

对于oldName的所有这些值, newName 2000s将被映射。

更新 ︰原因我得到'空指针exception'那里,因为在第二列(nextRow.getCell(1))的一些单元格为空。

所以无论何时迭代器到达空单元格,它都会抛出空指针exception。 在这里您需要指定缺less单元策略

通过

 Cell cell2 = row.getCell(j,org.apache.poi.ss.usermodel.Row.CREATE_NULL_AS_BLANK); 

(它只是将空值视为空白)

这样,您也可以从Null值读取时解决Excel中的空指针exception