首页 > 解决方案 > 我正在尝试使用 Apache POI 库读取 excel 文件,但是当我尝试读取单元格类型时,我得到一个空指针异常

问题描述

我正在阅读一个 excel 文件:https ://drive.google.com/drive/u/0/folders/0AIRmPm_DPjucUk9PVA

现在,我要做的就是将这个 excel 文件中的每个条目打印到控制台,格式为:邮政编码 - 城市 - 州。现在,我要做的就是获取邮政编码。这是我的方法:

        FileInputStream inputStream = new FileInputStream("C:/Users/student/eclipse-workspace/Weather2/bin/resources/uszips.xlsx");
        Workbook workbook = new XSSFWorkbook(inputStream);
        Sheet firstSheet = workbook.getSheetAt(0);
        Iterator<Row> iterator = firstSheet.iterator();
        int i = 0;
        while(iterator.hasNext()) {
            Row nextRow = iterator.next();
            if(nextRow.getCell(i+1).getCellType().equals("NUMERIC") && nextRow.getCell(i).toString().length()==5) //this if statement is where the error occurs {
                System.out.println(nextRow.getCell(i).getNumericCellValue());
            }
            Iterator<Cell> cellIterator = nextRow.cellIterator();
            while(cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
            }
            i++;
        }
        workbook.close();
        inputStream.close();
    }
}

运行此方法时出现以下错误:

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.NullPointerException
    at Forecast.search_Zipcodes(Weather2.java:41)
    at Weather2.main(Weather2.java:94)
    ... 11 more
Exception running application Weather2

我不明白为什么我会收到空​​指针异常。我肯定知道单元格的值存在,还是其他东西的空指针异常?任何帮助将不胜感激,谢谢。

标签: javaexcelapache-poi

解决方案


空指针异常可能发生在两个语句之一中。

if(nextRow.getCell(i+1).getCellType().equals("NUMERIC") && nextRow.getCell(i).toString().length()==5)

要么在这个:nextRow.getCell(i+1)。getCellType() .equals("NUMERIC") 或者这个:nextRow.getCell(i)。toString() .length()==5

您必须提供没有单元格的索引。

我建议你放弃你的代码 if(nextRow.getCell(i+1).getCellType().equals("NUMERIC") && nextRow.getCell(i).toString().length()==5) //this if statement is where the error occurs { System.out.println(nextRow.getCell(i).getNumericCellValue()); }

并改用此代码,因为它无法生成空指针异常。(如果您不希望有任何空单元格。) while(cellIterator.hasNext()) { Cell cell = cellIterator.next(); }

否则如果要继续使用之前的代码,则需要将代码展开为多行并使用空值检查。例如。

Cell cell = nextRow.getCell(i+1);
if (cell != null) {
//do numeric and length check here
}

验证您的用法nextRow.getCell(i+1)nextRow.getCell(i)注意您第一次使用 i + 1 并在接下来使用 i。


推荐阅读