Java & Excel - 公式更新

Java & Excel - Formulas updating

我正在使用 Apache POI 将数据保存到 excel 文件。基本数据保存得很好,但我还需要使用公式。

它添加了公式,但在我刷新单元格(点击进入并按 enter)之前它不会被评估

我用来创建单元格的代码。删除了不相关的代码

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))");
        
        start++;
    }
}

这是公式

的结果

设置所有公式后运行解决了

FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
    for (Row r : sheet) {
        for (Cell c : r) {
            evaluator.evaluateFormulaCell(c);
        }
    }