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

旧巷老猫 提交于 2019-12-25 00:16:20

问题


I have an Excel Sheet where the Date Cell is assigned with the Date Formula in Excel TODAY() + 1. So basically today it's showing as 03/10/2018 by default. I've created a code to read the data from Excel which has the formula in it but when I'm getting the date it's coming differently.

Code :

  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;
              }
      }

I don't know why it's showing date from January with the formula applied TODAY() + 1

Similar to this another function TODAY() + 15 returning the 22-04-2018.


回答1:


As stated in 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!"

So all formulas will have cached results stored from the last time they were evaluated. This is either the last time the workbook was opened in Excel, recalculated and saved or from the last time an evaluation was be done outside of Excel.

So if a cell having the formula =TODAY() has a cached result of 22-01-2018 stored, then the workbook was evaluated on January 22, 2018 the last time.

To get always current formula results you need evaluating the formulas first before reading. Simplest way:

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

Or you are using a DataFormatter together with a FormulaEvaluator:

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


来源:https://stackoverflow.com/questions/52614364/how-to-retrieve-the-date-from-excel-with-formula-by-apache-poi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!