在Apache POI公式中引用工作表

时间:2010-06-21 09:25:49

标签: java excel excel-2003 formula apache-poi

我使用Apache POI 3.6生成excel(2003)表。我想在一个单元格中插入一个公式,该公式计算几张纸上某些单元格的总和。

我有一张名为a,b和c的图纸,想要计算单元格A1的总和

我试过了:

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

POI不会产生任何错误,但是当我打开工作表时,我在OpenOffice中收到错误:

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

我做了一些研究,显然在引用多张表时存在错误。 (例如https://issues.apache.org/bugzilla/show_bug.cgi?id=46670)有没有人知道如何在POI中使用多张表格的公式?

--------------源代码-------------------

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

}

1 个答案:

答案 0 :(得分:6)

如果您在填充单张纸张后将“总计”表单的创建移动到,您的代码将正常工作。

如下所示:

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

单元格Total!A1显示30