如何避免NullPointerException与使用POI的空单元格?

我试图从我的Java程序中使用Apache POI的Excel .xlsx文件中获得一些值,但我有麻烦,因为我的循环有时会遇到一个空的单元格,然后我得到一个NullPointerException。 在阅读之前如何“testing”细胞? 这是我的一段代码:

FileInputStream file = new FileInputStream(new File(file)); XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet = workbook.getSheetAt(0); int rows; rows = sheet.getPhysicalNumberOfRows(); for (int i=1;i<rows;i++){ Row row = sheet.getRow(i); Cell cell = row.getCell(2); // Here is the NullPointerException String cellString = cell.getStringCellValue(); myArrayList.add(cellString); } 

这使我:

 java.lang.NullPointerException at analyse.Analyser.getExcelWords3(Analyser.java:73) at analyse.Analyser.main(Analyser.java:21) 

我想知道是否有可能检查单元格是否是空的,然后再尝试阅读,那么我将不会得到NPE。 先谢谢你 !

将你的代码包装在一个try / catch语句中,这就是它的用途。https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

一些未经testing的代码给你的想法:

 for (int i=1;i<rows;i++){ try{ Row row = sheet.getRow(i); Cell cell = row.getCell(2); // Here is the NullPointerException String cellString = cell.getStringCellValue(); myArrayList.add(cellString); }catch(NullPointerException NPE) { //what to do when the exception occurs? } } 

看看这个方法:

 /** * Returns the cell at the given (0 based) index, with the specified {@link org.apache.poi.ss.usermodel.Row.MissingCellPolicy} * * @return the cell at the given (0 based) index * @throws IllegalArgumentException if cellnum < 0 or the specified MissingCellPolicy is invalid * @see Row#RETURN_NULL_AND_BLANK * @see Row#RETURN_BLANK_AS_NULL * @see Row#CREATE_NULL_AS_BLANK */ public XSSFCell getCell(int cellnum, MissingCellPolicy policy) { 

它应该帮助你。

 ` FileInputStream file = new FileInputStream(new File(file)); XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet = workbook.getSheetAt(0); int rows; String cellString = null; rows = sheet.getPhysicalNumberOfRows(); for (int i=1;i<rows;i++){ Row row = sheet.getRow(i); if(row.getCell(2) == null) { cellString = null; } else { Cell cell = row.getCell(2); //if 3rd column of excelsheet then getCell(2).. cellString = cell.getStringCellValue(); } myArrayList.add(cellString); } if excel cell contain empty/blank then it will be stored as null`