Java POI : How to read Excel cell value and not the formula computing it?

后端 未结 5 651
借酒劲吻你
借酒劲吻你 2020-12-12 22:42

I am using Apache POI API to getting values from an Excel file. Everything is working great except with cells containing formulas. In fact, the cell.getStringCellValu

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 23:17

    For formula cells, excel stores two things. One is the Formula itself, the other is the "cached" value (the last value that the forumla was evaluated as)

    If you want to get the last cached value (which may no longer be correct, but as long as Excel saved the file and you haven't changed it it should be), you'll want something like:

     for(Cell cell : row) {
         if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            System.out.println("Formula is " + cell.getCellFormula());
            switch(cell.getCachedFormulaResultType()) {
                case Cell.CELL_TYPE_NUMERIC:
                    System.out.println("Last evaluated as: " + cell.getNumericCellValue());
                    break;
                case Cell.CELL_TYPE_STRING:
                    System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
                    break;
            }
         }
     }
    

提交回复
热议问题