从Excel表格读取数据时得到NullpointerException

我试图从Excel表读取数据,但每次读取单元格索引= 6时的数据时都得到NullPointerException。 把while(value!= null)设置为空值,但是仍然没有任何输出。 我正在把excel表格的屏幕截图从我想要获取数据的地方放入。 在这里输入图像描述

Code- package com.selenium; import java.io.FileInputStream; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.io.IOException; public class Exxcel { public static void main(String[] args) throws Exception,NullPointerException{ //WebDriver driver= new FirefoxDriver(); //WebElement wb; try{ FileInputStream file= new FileInputStream("C:\\Documents and Settings\\OMEGA\\Desktop\\Test Planning And Documents\\Automation Data.xlsx"); Workbook data=WorkbookFactory.create(file); Sheet sheet=data.getSheet("Sheet1"); for(int i=1;i<=sheet.getLastRowNum();i++){ Row row= sheet.getRow(i); int j=0; String value=row.getCell(j).getStringCellValue(); while(value != null){ System.out.println(value); }//while while(value == null){ j++; } }//for /*while(j1==9){ String value=row.getCell(j1).getStringCellValue(); System.out.println(value); }//while2 */ }catch(NullPointerException n){n.printStackTrace(); System.out.println("Null"); }// catch }//main }//class StackTrace- Null java.lang.NullPointerException at com.selenium.Exxcel.main(Exxcel.java:22) 

检查row.getCell(j).getStringCellValue() != null是不够的。 你应该检查row.getCell(j) != null

另外,你的while循环没有意义:

第一个将无所事事或永远打印价值(因为你没有改变循环内的价值)。

  while(value != null) { System.out.println(value); }//while 

第二个将无所事事或永远增加j(因为你没有改变循环内的值)。

  while(value == null) { j++; } 

我build议你用下面的代码replace它们:

 Row row = sheet.getRow(i); if (row != null) { for (int j = 0; j < row.getLastCellNum(); j++) { if (row.getCell(j) != null) { if (row.getCell(j).getCellType() == CELL_TYPE_STRING) { String value=row.getCell(j).getStringCellValue(); if(value != null) { System.out.println(value); } } } } }