从Excel Sheet读取数据时得到NullpointerException

时间:2014-07-05 18:37:32

标签: java excel vba excel-vba selenium-webdriver

我正在尝试从Excel工作表中读取数据,但每次读取单元格索引= 6时的数据时都会获取NullPointerException。 put while(value!= null)以避免空值但仍然得到没有任何输出的异常。 我正在从我试图获取数据的地方放置excel表的屏幕截图。 enter image description here

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)

1 个答案:

答案 0 :(得分:3)

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

另外,你的while循环毫无意义:

第一个将永远不执行任何操作或永久打印值(因为您没有在循环内更改值)。

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

第二个将不执行任何操作或永久增加j(因为您没有更改循环内的值)。

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

我建议您使用以下代码替换它们:

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);
                }
            }
        }   
    }
}
相关问题