How to set formulas in cells using Apache POI?

vamsi picture vamsi · Feb 26, 2010 · Viewed 84.8k times · Source

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.

Answer

user257111 picture user257111 · Feb 26, 2010

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