2016-05-13 342 views
0

我讀取了一個excel文件以傳遞某些數據字段的輸入。但是當我運行程序時,一些單元格值返回爲空,有些爲空白。實際上,當我打開Excel文件時,單元格中沒有可用的值。如何在讀取excel文件時識別單元格爲空或空或空

如何手動識別excel單元爲空或空白。

對於某些場景,我需要將空白值傳遞給字段。 如果單元格爲空,我無法將值傳遞給字段。

指導我伸出手。

代碼:

public static void readAllData() throws IOException{ 

    Object result = null; 

    String sheetName = "Testsheet"; 

    String filePathxlsx = "C:/Users/MSTEMP/Documents/Files/Testxssf.xlsx"; 

    try 

    { 

    FileInputStream in = new FileInputStream(filePathxlsx); 

    File file = new File(filePathxlsx); 



    if(file.isFile() && file.exists()){ 

     XSSFWorkbook xworkbook = new XSSFWorkbook(in); 
     XSSFSheet xsheet=xworkbook.getSheet(sheetName); 
     int totalRows = xsheet.getLastRowNum(); 

     for(int row =1; row<totalRows;row++){ 
      xrow=xsheet.getRow(row); 
      int totalCells=xrow.getLastCellNum(); 

      for(int cell =0; cell<totalCells;cell++){ 
       if(xrow != null) 
       { 
        xcell= xrow.getCell(cell); 

        if(xcell!=null) 
        { 
         switch (xcell.getCellType()) { 

          case Cell.CELL_TYPE_NUMERIC:// numeric value in excel 
           if(DateUtil.isCellDateFormatted(xcell)){ 

            Date myDate = xcell.getDateCellValue(); 
            SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy", Locale.US); 
            result = formatter.format(myDate); 
            //System.out.println("Today : " + result); 
           } 
           else{ 
            result = new BigDecimal(xcell.getNumericCellValue()).toPlainString(); 
           } 
           break; 

          case Cell.CELL_TYPE_STRING: // string value in excel 
           result = xcell.getStringCellValue(); 
           break; 

          case Cell.CELL_TYPE_BOOLEAN: // boolean value in excel 
           result = xcell.getBooleanCellValue(); 
           break; 

          case Cell.CELL_TYPE_BLANK: // blank value in excel 
           result = xcell.getStringCellValue(); 
           break; 

          case Cell.CELL_TYPE_ERROR: // Error value in excel 
           result = xcell.getErrorCellValue()+""; 
           break; 
          } 
         } 
         else 
         { 
          System.out.println("Cell is empty"); 
         } 
        System.out.println("Value "+result); 
       } 
       else 
       { 
        System.out.println("Row is empty"); 
       } 
      }  
     } 
    } 
    inputStream.close(); 
} 
catch (Exception ex){ 
    ex.printStackTrace(); 
} 

}

回答

1

不知道爲什麼你要手動確定的細胞類型,但如果你想治療的情況下「零」或「空白」作爲一個單一的情況下,你可以使用Row.getCell的其他版本,該版本的第二個參數指定missing cell policy

這樣:

xcell= xrow.getCell(cell); 

將變爲:

xcell = xrow.getCell(cell, Row.RETURN_NULL_AS_BLANK); 

所以在任何情況下,電池具有值或爲空,但不能爲null。

相關問題