Is there a way to update formula references when copying a formula in Apache POI?
Say in Excel you have in row 1 the formula =A1/B1
. If you copy-paste it, say in row 5, the formula becomes =A5/B5.
In Apache POI if you run the lines
r5.getCell(2).setCellType(CellType.FORMULA);
r5.getCell(2).setCellFormula(r1.getCell(2).getCellFormula());
the formula remains =A1/B1
.
Your code is not copy/pasting something but gets the formula string from one cell and sets exactly this formula string to another cell. This will not changing the formula string. How even should it do?
So the need is to get the the formula string from one cell and then adjust this formula string to the target cell.
Since
apache poi
is able to evaluate formulas, it must also be able to parse formulas. The parsing classes are in the packages org.apache.poi.ss.formula and org.apache.poi.ss.formula.ptg.So we can use those classes to adjust the formula string to the target cell.
Example:
Following Excel workbook:
and following code:
leads to following output: