Selenium从Excel文件中读取数据

时间:2017-04-07 21:12:32

标签: java excel selenium nullpointerexception

我正在尝试从Excel文件中读取一些测试数据(3行和2列,中间没有空行),但在输出中我只得到Excel的第一行。之后,它给了我一个空指针异常。

public class ReadDataFromExcel {

    public void readExcel(String filePath,String fileName,String sheetName) throws IOException {

        File file =    new File(filePath+"\\"+fileName);
        FileInputStream inputStream = new FileInputStream(file);
        Workbook myWorkbook = null; 
        String fileExtensionName = fileName.substring(fileName.indexOf("."));

        if(fileExtensionName.equals(".xlsx")) {
            myWorkbook = new XSSFWorkbook(inputStream);
        }
        else if(fileExtensionName.equals(".xls")) {
            myWorkbook = new HSSFWorkbook(inputStream);    
        }

        Sheet mySheet = myWorkbook.getSheet(sheetName);    
        int rowCount = mySheet.getLastRowNum()- guru99Sheet.getFirstRowNum();
        System.out.println("Total rows= " +rowCount);   

        for (int i = 0; i < rowCount+1; i++) {   
            Row row = mySheet.getRow(i);
            int columnCount = row.getLastCellNum() - row.getFirstCellNum();           

            for(int j=0; j <= columnCount; j++) {                               
                System.out.print(row.getCell(j).getStringCellValue()+"|| ");
            }
            System.out.println();
        }
    }

    public static void main(String...strings) throws IOException {

        ReadDataFromExcel objExcelFile = new ReadDataFromExcel();
        String filePath = System.getProperty("user.dir")+"\\src\\testFileInputOutput";
        objExcelFile.readExcel(filePath,"testExcel.xlsx","testSheet");
    } 
}

我在这一行得到了例外:  System.out.print(row.getCell(j).getStringCellValue()+"|| ");

1 个答案:

答案 0 :(得分:0)

要通过NullPointerException,您可以通过用以下命令替换抛出异常的行来检查null:

Cell cell = row.getCell(j);
if (cell != null) {
    System.out.print(cell.getStringCellValue());
}
System.out.print("|| ");