How to retrieve the Date from Excel with Formula b

2019-08-20 12:37发布

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条回答
闹够了就滚
2楼-- · 2019-08-20 13:32

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);
...
查看更多
登录 后发表回答