Question

How to set formulas in cells using Apache POI?

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 the formula include the formula as a string, rather than the value the formula should have returned.

 45  114203  45
1 Jan 1970

Solution

 60

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);
2010-02-26

Solution

 20

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);

UPDATE

setCellType() :Based on @fenix comment. This method is deprecated and will be removed in POI 5.0. Use explicit setCellFormula(String), setCellValue(...) or setBlank() to get the desired result.

String formula= "SUM(B4:B20)";
cell.setCellFormula(formula);
2017-04-26