使用Apache POI Java从Excel获取具有日期公式的单元格的日期值

时间:2017-06-22 14:32:21

标签: java excel excel-formula apache-poi

我试图从excel文件中读取一切正常单元格值的工作。但是当涉及公式,尤其是日期字段时,我无法获得任何日期值。

Date generated using formula in excel

如何在Evaluated CellValue中检查日期类型?以及如何获得日期值?

我的代码如下。

Cell cell = nextRow.getCell(cellIndex, Row.CREATE_NULL_AS_BLANK);
if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
    FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
    CellValue formulaValue = evaluator.evaluate(cell);
    switch (formulaValue.getCellType()) {
        case Cell.CELL_TYPE_NUMERIC: {
            int numbericValue = formulaValue.getNumericValue(); // 42909.0
            if (isCellDate?) { //What should i check here?
                // DATE THINGS
                // how to convert numeric value 42909.0 to date??
            } else {
               // NUMERIC THINGS 
            }
            break;
        }
        default:
            // STRING - ERROR - BLANK - NUMERIC THINGS 
            break;
    }
}

1 个答案:

答案 0 :(得分:1)

HSSFDateUtil : Helped to solve my issue. my solution is :

case Cell.CELL_TYPE_NUMERIC: {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
    Date date = HSSFDateUtil.getJavaDate(formulaValue.getNumberValue());
    System.out.println(date);
} else {
    System.out.println(cell.getNumericCellValue());
}
break;

}