Apache POI evaluate formula

后端 未结 4 679
逝去的感伤
逝去的感伤 2020-12-01 21:41

I have some formulas in cells of my sheet, and I want to evaluate them after I insert some values. Ex :

My formula is =SUM(B1,B2)

Before values

相关标签:
4条回答
  • 2020-12-01 22:18

    if you using HSSF try :

    HSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);
    
    0 讨论(0)
  • 2020-12-01 22:19

    You can use this.

     public static void triggerFormula(HSSFWorkbook workbook){      
    
                    FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
                    HSSFSheet sheet = workbook.getSheetAt(0);
                    int lastRowNo=sheet.getLastRowNum();        
    
                    for(int rownum=0;rownum<=lastRowNo;rownum++){
                    Row row;
                     if (sheet.getRow(rownum)!=null){
                             row= sheet.getRow(rownum);
    
                          int lastCellNo=row.getLastCellNum();
    
                              for(int cellnum=0;cellnum<lastCellNo;cellnum++){  
                                      Cell cell;
                                      if(row.getCell(cellnum)!=null){
                                         cell = row.getCell(cellnum);   
                                        if(Cell.CELL_TYPE_FORMULA==cell.getCellType()){
                                        evaluator.evaluateFormulaCell(cell);
                                    }
                                }
                             }
                     }
                    }
    
    
                }
    
    0 讨论(0)
  • 2020-12-01 22:27

    To promote a comment to an answer...

    You firstly need to ensure you're using the same version of POI for the main jar, and the OOXML part. Your maven snippet was showing 3.7 for one, and 3.8 beta 1 for the other. You need to make sure they're both the same. (You might even want to use 3.8-beta2 which is just out).

    Then, use either:

    FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
    evaluator.evaluateFormulaCell(cell);
    

    or:

    XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
    

    See http://poi.apache.org/spreadsheet/eval.html for more details

    0 讨论(0)
  • 2020-12-01 22:33

    Perhaps XSSFFormulaEvaluator.evaluateAllFormulaCells(XSSFWorkbook wb) ?

    (or more specifically: evaluateFormulaCell(Cell cell).)

    If it doesn't work: what version of POI are you using? Formulas in XSSF are supported from v3.5.

    Also, try to use XSSFCreationHelper to instantiate your Formula Evaluator as suggested by the POI docs.

    0 讨论(0)
提交回复
热议问题