How to set formulas in cells using Apache POI?

后端 未结 7 1606
慢半拍i
慢半拍i 2021-01-01 09:09

I am currently using Apache POI for Java to set formulas in cells.

But after I run the program and open the Excel file that I created and processed, the cells with t

相关标签:
7条回答
  • 2021-01-01 09:17

    The below code worked fine for me, hope this could be useful to someone.

    cell.setCellType(Cell.CELL_TYPE_FORMULA);
    cell.setCellFormula("SUM(C70:C76)");
    
    0 讨论(0)
  • 2021-01-01 09:18

    Here is one suggested way:

    Workbook workbook1 = new SXSSFWorkbook(-1);
    Sheet newSheet = workbook1.createSheet("Valuations");
    Row newRow = newSheet.createRow(i-1);
    newRow.createCell(L++).setCellFormula("AVERAGE(" + "E" + i + ":" + "G" + i + ")");
    

    Where E and G are the columns like A1,B1,C1....E1...G1
    and i represent a number in the above Column.

    L++ is simply an incremental counter.

    0 讨论(0)
  • 2021-01-01 09:20

    You could use this to evaluate the formulas in the workbook:

            // Evaluate all formulas in the sheet, to update their value
        FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
        formulaEvaluator.evaluateAll();
    
    0 讨论(0)
  • 2021-01-01 09:21

    Cell Constants are deprecated and will be removed from version 4.0 instead of Cell Use

    CellType.FORMULA

    String formula= "SUM(B4:B20)";
    cell.setCellType(CellType.FORMULA);
    cell.setCellFormula(formula);
    
    0 讨论(0)
  • 2021-01-01 09:24

    Apache POI does not support user-defined functions.

    From the documentation:

    Note that user-defined functions are not supported, and is not likely to done any time soon... at least, not till there is a VB implementation in Java!

    0 讨论(0)
  • 2021-01-01 09:28

    The HSSFCell object has methods .setCellType and .setCellFormula which you need to call like this:

    // "cell" object previously created or looked up
    String strFormula= "SUM(A1:A10)";
    cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
    cell.setCellFormula(strFormula);
    
    0 讨论(0)
提交回复
热议问题