2016-09-22 70 views
0

我的excel表格如下:空白單元格檢查,以避免空指針異常

Property_id Property_Name        
3    Hilton         
Season_start_date Season_end_date MSG Sun Mon Tues Wed Thurs Fri Sat 
9/16/1999   9/16/1999  fxb 100 100 100 100 100 100 100 
9/16/1999   9/16/1999  fb 100 100 100 100 100 100 100 
9/16/1999   9/16/1999  tfg 100 100 100 100 100 100 100 

我用下面的代碼來檢測它:

  Iterator<Cell> cellIterator = row.cellIterator(); 

      while (cellIterator.hasNext()) { 
       Cell cell = cellIterator.next(); 
       // Check the cell type and format accordingly 

       switch (cell.getCellType()) { 
       case Cell.CELL_TYPE_BLANK: 
        throw new IOException("Cell empty "+cell.getColumnIndex() + cell.getRowIndex()); 

       case Cell.CELL_TYPE_NUMERIC: 
        System.out.print(cell.getNumericCellValue() + "\t"); 
        this.propertyId = cell.getNumericCellValue(); 
        break; 
       case Cell.CELL_TYPE_STRING: 
        System.out.print(cell.getStringCellValue() + "\t"); 
        this.propertyName = cell.getStringCellValue(); 
        break; 
       } 
      } 
      ExcelToDatabase data = new ExcelToDatabase(); 
      if (data.existingId(propertyId) == 0){ 
       data.propertyDetails(propertyId, propertyName); 
       data.createTable(propertyName); 
      } 

但是這個代碼是給空白單元格甚至property_name旁邊的單元格。你能告訴我在遇到空白單元時應該用什麼來拋出異常。

我也試過:

if (cell == null) 
    { 
     throw new IOException("blank cell "); 

    } 

但是,這並不工作..沒有異常被拋出

回答

0

我不知道爲什麼你想要拋出異常每當你遇到的空白單元格。我想你的問題可能會解決,如果你忽略空白單元格。

switch (cell.getCellType()) { 
      case Cell.CELL_TYPE_NUMERIC: 
       System.out.print(cell.getNumericCellValue() + "\t"); 
       this.propertyId = cell.getNumericCellValue(); 
       break; 
      case Cell.CELL_TYPE_STRING: 
       System.out.print(cell.getStringCellValue() + "\t"); 
       this.propertyName = cell.getStringCellValue(); 
       break; 
      default; 
       break; 

      } 
+0

拋出一個異常,你無法像寫東西休息後..默認也給不需要的細胞被宣佈爲空白 –

+0

我不明白你爲什麼要拋出的異常的空白單元格同樣的問題。 – puru

+0

我想檢查用戶是否有錯誤在我的表格中留下一個空格 –