2015-02-12 104 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线程可能会回答您的后续问题。