如何使用 Apache POI 的公式从 Excel 中检索日期

How to retrieve the Date from Excel with Formula by Apache POI

我有一个 Excel Sheet,其中日期单元格分配有 Excel TODAY() + 1 中的日期公式。所以基本上今天它默认显示为 03/10/2018。我创建了一个代码来读取 Excel 中的数据,其中包含公式,但是当我获取日期时,它会有所不同。

代码:

  Cell c = CellUtil.getCell(r, columnIndex);
  CellType type = c.getCellType();
      if (type == CellType.FORMULA) {
          switch (c.getCachedFormulaResultType()) {
                 case NUMERIC:
                      if (DateUtil.isCellDateFormatted(c)) {
                          value = (new SimpleDateFormat("dd-MM-yyyy").format(c.getDateCellValue()));
                          data.add(value); // Date should display 03-10-2018 but it's showing 23-01-2018
                      } else {
                          value = (c.getNumericCellValue()) + "";
                          data.add(value);
                      }
                  break;
                  case STRING:
                           value = c.getStringCellValue();
                           data = new LinkedList <String>(Arrays.asList(value.split(";")));
                   break;
              }
      }

我不知道为什么它显示的日期是 1 月份应用的公式 TODAY() + 1

与此类似的另一个函数 TODAY() + 15 返回 22-04-2018。

Formula Evaluation所述:

"The Excel file format (both .xls and .xlsx) stores a "cached" result for every formula along with the formula itself. This means that when the file is opened, it can be quickly displayed, without needing to spend a long time calculating all of the formula results. It also means that when reading a file through Apache POI, the result is quickly available to you too!"

因此所有公式都将缓存上次计算的结果。这是上次在 Excel 中打开工作簿、重新计算和保存的时间,或者是上次在 Excel.

之外进行评估的时间

因此,如果具有公式 =TODAY() 的单元格存储了 22-01-2018 的缓存结果,则工作簿最后一次评估是在 2018 年 1 月 22 日。

要始终获得最新的公式结果,您需要 evaluating the formulas first 才能阅读。最简单的方法:

...
workbook.getCreationHelper().createFormulaEvaluator().evaluateAll();
...

或者您正在使用 DataFormatter together with a FormulaEvaluator

...
DataFormatter formatter = new DataFormatter(); 
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); 
...
Cell cell = CellUtil.getCell(...);
...
String value = formatter.formatCellValue(cell, evaluator);
...