使用POI HSSF API从excel单元格中读取日期值

时间:2009-05-14 06:43:35

标签: java excel apache-poi poi-hssf

我正在使用POI HSSF API进行Java中的excel操作。我在我的一个excel单元格中有一个日期值“8/1/2009”,当我尝试使用HSSF API读取该值时,它会将单元格类型检测为Numeric并返回我的日期的“Double”值。请参阅以下示例代码:

cell = row.getCell(); // date in the cell '8/1/2009'
switch (cell.getCellType()) {

case HSSFCell.CELL_TYPE_STRING:
    cellValue = cell.getRichStringCellValue().getString();
    break;
case HSSFCell.CELL_TYPE_NUMERIC:
    cellValue = new Double(cell.getNumericCellValue()).toString();
    break;
default:
}

Cell.getCellType()返回NUMERIC_TYPE,因此此代码将日期转换为double! :(

有没有办法在HSSF POI中读取日期!?

5 个答案:

答案 0 :(得分:37)

你可以看看:

HSSFDateUtil.isCellDateFormatted()

有关HSSFDateUtil的更多详细信息,请参阅POI可怕的电子表格格式API:

http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFDateUtil.html

这也提供了一些帮助方法来返回Excel getExcelDate()和Java日期getJavaDate()。你需要对不同的日期格式保持警惕......

答案 1 :(得分:21)

如果要以与Excel文件中相同的格式引用日期,则应使用CellDateFormatter。示例代码:

CellValue cValue = formulaEv.evaluate(cell);
double dv = cValue.getNumberValue();
if (HSSFDateUtil.isCellDateFormatted(cell)) {
    Date date = HSSFDateUtil.getJavaDate(dv);

    String dateFmt = cell.getCellStyle().getDataFormatString();
    /* strValue = new SimpleDateFormat(dateFmt).format(date); - won't work as 
    Java fmt differs from Excel fmt. If Excel date format is mm/dd/yyyy, Java 
    will always be 00 for date since "m" is minutes of the hour.*/

    strValue = new CellDateFormatter(dateFmt).format(date); 
    // takes care of idiosyncrasies of Excel
}

答案 2 :(得分:6)

Excel将日期和时间视为数字...... Jon说得更好,所以我不会在这里回应他......

但是,您在问题中提供的示例代码位于http://poi.apache.org/spreadsheet/quick-guide.html#CellContents

答案 3 :(得分:6)

如果您使用POI 3.5,则可以使用以下

cell.getDateCellValue()方法。这也适用于excel 2007。

答案 4 :(得分:0)

由于POI 3.15 beta3,一些功能是deprecated。 您可以检查数据格式并检索为Java Date

SimpleDateFormat format = new SimpleDateFormat("");
String cellValue;
if(cell != null && cell.getCellTypeEnum() != CellType.STRING &&
    cell.getCellTypeEnum() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)){

    cellValue = format.format(cell.getDateCellValue());
}
相关问题