Reputation: 1462
I am trying to read data from a excel sheet but getting NullPointerException every time when reading data at the cell index =6. Put while(value != null) to avoid null values but still got the exception without any output.
I am putting the screen shot of excel sheet from where i am trying to get data.
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)
Upvotes: 1
Views: 10323
Reputation: 393846
It's not enough to check that row.getCell(j).getStringCellValue() != null
. You should check that row.getCell(j) != null
.
In addition, your while loops makes no sense :
The first one will either do nothing or print value forever (since you are not changing value inside the loop).
while(value != null) {
System.out.println(value);
}//while
The second one will either do nothing or increment j forever (since you are not changing value inside the loop).
while(value == null) {
j++;
}
I suggest you replace them with the following code :
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);
}
}
}
}
}
Upvotes: 3