2015-02-12 121 views
3

我想在Java POI中讀取日期(yyyy-MM-dd)。Java POI - 從Excel文件中讀取日期

Cell cell = cellIterator.next(); 
cell.setCellType(Cell.CELL_TYPE_STRING); 

switch(cell.getCellType()){ 
    case Cell.CELL_TYPE_STRING: 
     if(DateUtil.isCellDateFormatted(cell)){ [ERROR HERE] 
       System.out.print(cell.getDateCellValue() + "\t\t"); 
     }else{ 
       System.out.print(cell.getStringCellValue() + "\t\t"); 
     } 
    case Cell.CELL_TYPE_NUMERIC: 
     System.out.print(cell.getNumericCellValue() + "\t\t"); 
     break; 
    case Cell.CELL_TYPE_BOOLEAN: 
     System.out.print(cell.getBooleanCellValue() + "\t\t"); 
     break; 
} 

不過,我得到以下錯誤:

Exception in thread "main" java.lang.IllegalStateException: Cannot get a numeric value from a text cell 
at org.apache.poi.xssf.usermodel.XSSFCell.typeMismatch(XSSFCell.java:882) 
at org.apache.poi.xssf.usermodel.XSSFCell.getNumericCellValue(XSSFCell.java:220) 
at org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(DateUtil.java:495) 
at others.ReadDateTime.main(ReadDateTime.java:44) 
Java Result: 1 

我應該如何糾正呢?

回答

7

日期不能存儲在CELL_TYPE_STRING單元格中。您應該將其存儲在CELL_TYPE_NUMERIC單元格中。詳情請參閱here

您還錯過了break關鍵字後首先case。因此,如果單元格是Cell.CELL_TYPE_STRING,那麼也是

System.out.print(cell.getNumericCellValue() + "\t\t"); 

被調用。

所以它應該是:

switch(cell.getCellType()) { 
    case Cell.CELL_TYPE_STRING: 
     System.out.print(cell.getStringCellValue() + "\t\t"); 
     break; 
    case Cell.CELL_TYPE_NUMERIC: 
     if (DateUtil.isCellDateFormatted(cell)) { 
      SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); 
      System.out.print(dateFormat.format(cell.getDateCellValue()) + "\t\t"); 
     } else { 
      System.out.print(cell.getNumericCellValue() + "\t\t"); 
     } 
     break; 
    case Cell.CELL_TYPE_BOOLEAN: 
     System.out.print(cell.getBooleanCellValue() + "\t\t"); 
     break; 
} 
+0

從上面的代碼,輸出顯示爲整數。如何使日期格式爲(dd-mm-YYYY)? – 2015-02-12 07:16:01

+0

@MichaelKuan請注意,格式中的「mm」表示分鐘,而「MM」表示月份。 – rtruszk 2015-02-12 07:31:03

+0

好的。我知道了。謝謝。 – 2015-02-12 07:41:29

3

這是Apache POI tutorial直接挑,你讓想參觀,並獲得更多的細節。

switch (cell.getCellType()) { 
       case Cell.CELL_TYPE_STRING: 
        System.out.println(cell.getRichStringCellValue().getString()); 
        break; 
       case Cell.CELL_TYPE_NUMERIC: 
        if (DateUtil.isCellDateFormatted(cell)) { 
         System.out.println(cell.getDateCellValue()); 
        } else { 
         System.out.println(cell.getNumericCellValue()); 
        } 
        break; 
       case Cell.CELL_TYPE_BOOLEAN: 
        System.out.println(cell.getBooleanCellValue()); 
        break; 
       case Cell.CELL_TYPE_FORMULA: 
        System.out.println(cell.getCellFormula()); 
        break; 
       default: 
        System.out.println(); 
      } 

格式日期:This線程可能會回答您的後續問題。