Search code examples
coldfusionapache-poicoldfusion-9

Force full calculation of entire workbook in Coldfusion / Apache POI


Given a workbook with cross-sheet formulas generated by Coldfusion 9 via Apache POI.

I want to programmatically force an entire workbook to do a "full calculation with dependency tree rebuild" before saving the workbook to disk.

So that when my end-users open the spreadsheet, they do not have to press Ctrl-Alt-Shift-F9.

How do I accomplish this in coldfusion?

References:


Solution

  • Unfortunately there is no easy answer to this one.

    Option 1:

    I think the shortest route is to use CreationHelper.createFormulaEvaluator().evaluateAll(). Unfortunately, it is not available in CF9. That method was added in a later version of POI than the one shipped with CF9. The same applies to setForceFormulaRecalculation(). You could probably use the JavaLoader.cfc to load a newer version of POI. Then you would have access to those methods. But that may be more involved than you want for this one task.

    Option 2:

    Failing that, if you know the proper sequence you could iterate through the sheets and recalculate the formulas for each one:

    wb = sheet.getWorkBook();
    evaluator = wb.getCreationHelper().createFormulaEvaluator();
    // you could also use an array of sheet names instead
    for(sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) {
        poiSheet = wb.getSheetAt(sheetNum);
        rows = poiSheet.rowIterator();
        while (rows.hasNext()) {
            r = rows.next();
            cells = r.cellIterator();
            while (cells.hasNext()) {
                c = cells.next();
                if (c.getCellType() == c.CELL_TYPE_FORMULA) {
                    evaluator.evaluateFormulaCell(c);
                }
            }
        }
    }
    

    Option 3:

    Another possibility is to populate a template with a macro which automatically recalculates when the workbook opens. The obvious disadvantage is it relies on a macro. But since it is performed by Excel itself, it is probably the most reliable/robust option.