0

I'm using Apache POI to save data to an excel file. Basic data is being saved fine, but I need to also use formula's.

Its adding the formula in, but its not being evaluated until I refresh the cell (clicking into and pressing enter)

The code I'm using to create the cells. Removed code that's not relevant

public void writeExcel(ClassManager cm) throws FileNotFoundException, IOException {
    setupRows();
    workbook.setForceFormulaRecalculation(true);

    FileOutputStream outputStream = new FileOutputStream(fileLocation);
    workbook.write(outputStream);
    workbook.close();
}

public void setupRows() {
    setupRow15();
}

public void setupRow15() {
    int start = 2;
    Row row = sheet.createRow(16);
    
    // Create 1st Cell
    Cell cell = row.createCell(0);
    cell.setCellValue("templateId = ");
        
    for (int i = 0; i < classes.size(); i++) {
        // Get class
        Classes c = classes.get(i);
        
        // Create cell
        cell = row.createCell(start);
        
        // Set contents
        cell.setCellFormula("IF(C3=\"\",\"\",CONCAT($A17,$B17,C" + (start + 1) + ",$B17,$A$16))");
        
        start++;
    }
}

It's resulting in the formula

1
  • Have you reviewed formula evaluation? (Side note: Is that final sentence in your question incomplete?) Commented Jan 15, 2021 at 20:29

1 Answer 1

1

Solved it by running after setting all formulas

FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
    for (Row r : sheet) {
        for (Cell c : r) {
            evaluator.evaluateFormulaCell(c);
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.