简体   繁体   中英

Excel formula not updating on row delete from java application using Apache POI

I'm using Apache POI in my application to write data to an excel file. I've an excel file template and a few formulas are also there in it. In my application, i use the excel template, write into it ,then delete unused rows and calculate formulas in the end. I'm using SUM formula in the file. The problem is when rows are deleted, the SUM formula is not updating,due to which error values are coming up in excel.

Example : the formula being used is : for cell B215 : SUM(B15:B214). in the application,after writing to the file i delete unused rows. now I've data till 70th row in the file.All other rows have been deleted. So my formula should get updated to : SUM(B15:B69) for cell B70. But in the file it's still showing the formula as SUM(B15:B214). Hence the value of that cell is "VALUE#

Code snippet :

File file = new File(path)
InputStream is = new FileInputStream(file)
POIFSFileSystem fs = new POIFSFileSystem(is)
HSSFWorkbook wb = new HSSFWorkbook(fs)
HSSFSheet excelSheet
int[] indexArray = populateSheet(excelSheet)

//indexArray is array with 3 values as startrow, lastrow, and first empty row.

removeBlankRows(excelSheet,indexArray)



//evaluate formula

FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator()
for(HSSFRow r : excelSheet) {
 for(HSSFCell c : r) {
  if(c.getCellType() == Cell.CELL_TYPE_FORMULA) {
    String formula = c.getCellFormula();
    evaluator.evaluateFormulaCell(c)
    }
 }
}

private void removeBlankRows(HSSFSheet sheet, int[] shiftInfo){
        for(int i = shiftInfo[2]; i <= shiftInfo[1]; ++i) {
            sheet.removeRow(sheet.getRow(i))
        }
        //Shift up the rows
        def startRow = shiftInfo[1]+1
        def endRow = sheet.getLastRowNum()
        def rowCount = -1* (shiftInfo[1] - shiftInfo[2] + 1)
        sheet.shiftRows(startRow, endRow, rowCount)
    }

This is an Excel bug. I've dealt with this in the past by doing the following:

  1. Label the sum cell BSUM
  2. We need a stable range that won't be affected by inserts/deletes. Add a formula to a safe (one that won't get deleted) cell, for this example D15: ="B15:B"&ROW(BSUM)-1 This will produce a stable range.
  3. Use INDIRECT in the BSUM cell like so:
    =SUM(INDIRECT(D15))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM