我正在编写一个脚本,它解析 Excel 工作表中的每一行并打印出该行中每个单元格的内容。这是代码:
for(int cntr=1; cntr<=firstSheet.getPhysicalNumberOfRows(); cntr++){
Row currentRow = firstSheet.getRow(cntr);
System.out.println("-------------Working on Row Number: "+currentRow.getRowNum());
for(int cntr2 = 0; cntr2<currentRow.getLastCellNum(); cntr2++){
Cell currentCell = currentRow.getCell(cntr2, Row.RETURN_NULL_AND_BLANK);
if(currentCell==null){
//cell doesn't have anything in there
System.out.println("Cell in Row number "+(currentRow.getRowNum()+1)+" is null.");
}
switch(currentCell.getCellType()){
case Cell.CELL_TYPE_STRING:
System.out.println("Current Cell: "+currentCell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println("Current Cell: "+currentCell.getNumericCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println("Current Cell: "+currentCell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_BLANK:
System.out.println("Cell in row number "+(currentRow.getRowNum()+1)+" is returned as blank");
break;
}
}
}
问题是,在我的 Excel 电子表格的第 11 行(如果从 0 开始计数,则为第 10 行)有一个单元格,准确地说是 3 个单元格,里面什么都没有。每次我的脚本到达这一点时,它都会抛出一个空指针异常并停止运行,尽管我的 IDE 说构建成功。我对如何处理这个问题进行了一些研究,并找到了我在该行中使用的 MissingCellPolicy
Cell currentCell = currentRow.getCell(cntr2, Row.RETURN_NULL_AND_BLANK);
但我仍然收到 NullPointerException 错误。我的算法有什么问题?
另外,这里是输出:
Exception in thread "main" java.lang.NullPointerException
...
-------------Working on Row Number: 10
Current Cell: OC[C@H]1OC(O)[C@H](O)[C@@H](O)[C@@H]1O
Current Cell: NCGC00159408-02
Current Cell: DL-Glucose
Current Cell: 180.16
Current Cell: -3.51
Current Cell: 6.0
Current Cell: 5.0
-------------Working on Row Number: 11
Current Cell: OC[C@@H](O)C(O)[C@@H](O)CO
Current Cell: NCGC00165982-01
Cell in Row number 11 is null.
at excellibrarycreation.ExcelFileProcesser.processFile(ExcelFileProcesser.java:64)
at excellibrarycreation.ExcelLibraryCreation.main(ExcelLibraryCreation.java:25)
Java 结果:1 构建成功(总时间:11 秒)