views:

37

answers:

1

Hello,

I am using apache POI 3.6 to generate excel (2003) sheets. I want to insert a formula to a cell which calculates a sum of a certain cells on several sheets.

I have sheets named a, b and c and want to calculate the sum the cells A1

I tried: cell.setCellFormula("a!A1+b!A1+c!A1"); POI does not produce any errors, but when I open the sheet i get an error in OpenOffice

Err: 522 - =$#REF!.A1+$#REF!.A1+$#REF!.A1

I did a bit of research and appearingly there are bugs when referencing multiple sheets. ( https://issues.apache.org/bugzilla/show_bug.cgi?id=46670) Does anyone have an idea how to use formulas using multiple sheets in POI.

Thanks a lot Marc

-------------- source code -------------------

public static void main(String args[]){
    Workbook wb = new HSSFWorkbook();
    CreationHelper createHelper = wb.getCreationHelper();
    Sheet sheet = wb.createSheet("Total");

    Row row = sheet.createRow((short)0);
    Cell cell = row.createCell(0);

    cell.setCellFormula("a!A1+b!A1+c!A1");

    Sheet sheet1 = wb.createSheet("a");
    Sheet sheet2 = wb.createSheet("b");
    Sheet sheet3 = wb.createSheet("c");
    Sheet sheet4 = wb.createSheet("d");

    createVal(sheet1, createHelper, 5);
    createVal(sheet2, createHelper, 10);
    createVal(sheet3, createHelper, 15);
    createVal(sheet4, createHelper, 20);

    try {
        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
        wb.write(fileOut);
        fileOut.close();
        System.out.println("done");
    } catch (IOException e) {
        e.printStackTrace();
    }   }

public static void createVal(Sheet sheet, CreationHelper createHelper, int i){
     Row row = sheet.createRow((short)0);
        // Create a cell and put a value in it.
        Cell cell = row.createCell(0);
        // Or do it on one line.
        row.createCell(0).setCellValue(i);

}
+2  A: 

Your code will work fine if you move the creaton of "Total" sheet to after populating the individual sheets.

Like below:

...    
    createVal(sheet1, createHelper, 5); 
    createVal(sheet2, createHelper, 10); 
    createVal(sheet3, createHelper, 15);
    createVal(sheet4, createHelper, 20); 

    Sheet sheet = wb.createSheet("Total"); 
    Row row = sheet.createRow((short)0); 
    Cell cell = row.createCell(0); 

    cell.setCellFormula("a!A1+b!A1+c!A1"); 

Cell Total!A1 shows 30

JoseK
Thanks a lot! Works completely fine
Marc Giombetti