无法在迭代器Apache POI中初始化变量

时间:2019-03-07 08:36:23

标签: java apache-poi

我试图将一些从Excel工作表中获得的值分配给以后将用于创建对象的变量。但是,当我初始化这些变量时,会收到NullPointerException。

String file = "tests-example.xlsx";
        try {

            FileInputStream excelFile = new FileInputStream(new File(file));
            Workbook workbook = new XSSFWorkbook(excelFile);
            Sheet datatypeSheet = workbook.getSheetAt(0);
            Iterator<Row> iterator = datatypeSheet.iterator();
            while (iterator.hasNext()) {
                 Row currentRow = iterator.next();
                 Iterator<Cell> cellIterator = currentRow.iterator();                 

                 while (cellIterator.hasNext()) {
                     Cell currentCell = cellIterator.next();
                     //when I comment out these two lines it works fine, but I need these
                     String foodName = currentRow.getCell(0).getStringCellValue();   
                     String foodType = currentRow.getCell(1).getStringCellValue();

                     //getCellTypeEnum shown as deprecated for version 3.15
                     //getCellTypeEnum ill be renamed to getCellType starting from version 4.0
                     if (currentCell.getCellTypeEnum() == CellType.STRING) {
                         System.out.print(currentCell.getStringCellValue() + "--");
                     } else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
                         System.out.print(currentCell.getNumericCellValue() + "--");
                     }

                }
                System.out.println();

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
   }

将打印所有值,然后引发NullPointerException。 Apache POI不允许这样做吗?提前致谢。

0 个答案:

没有答案