读取excel文件数据时获取空指针异常

时间:2018-05-29 12:02:58

标签: apache-poi

@Test
public void dataProviderMethod() throws InvocationTargetException, FileNotFoundException 
{
    try
    {
        File src=new File("D:\\TestData.xls");
        FileInputStream fis=new FileInputStream(src);
        HSSFWorkbook wb=new HSSFWorkbook(fis);
        HSSFSheet sheet = wb.getSheetAt(0);

        int rowcount=sheet.getLastRowNum()+1;

        System.out.println(rowcount);

        for(int i=1; i<rowcount;i++)
        {
            String questionType=sheet.getRow(i).getCell(0).getStringCellValue().toString();
            System.out.println(questionType);
        }

    }

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

}

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要修改代码逻辑,如下所示。因为,某些单元格具有空白值,因此抛出空指针异常。我们需要处理NULL Cell Value,如下所示

修改了For循环代码:

    //Column Index
    int column=0;
    for(int i=1; i<rowcount;i++){
        Row r=sheet.getRow(i);
        Cell c=r.getCell(column, Row.RETURN_BLANK_AS_NULL);

        if(c==null){
            questionType="";
        }
        else{
             questionType=r.getCell(column).getStringCellValue();
        }
        System.out.println(questionType);

    }
相关问题