2017-04-07 209 views
0

我想從Excel文件(3行和2列之間沒有空白行)讀取一些測試數據,但在輸出中,我只是獲取Excel的第一行。之後,它給了我一個空指針異常。Selenium從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()+"|| ");

回答

0

爲了突破NullPointerException異常,你可以檢查null通過更換與此拋出異常的行:

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