Refresh Pivot Table with Apache POI

2019-04-07 20:45发布

问题:

I'm currently working on a Java application that uses a template excel file that contains a pivot table.

The template file also has a data sheet that seeds the pivot table. This data sheet is dynamically loaded in the java application through the Apache POI api.

When I open the excel file I must refresh the Pivot table manually to get the data loaded correctly.

Is there any way to refresh the Pivot table with the POI api so I don't have to manually do it?

回答1:

You can simple activate an option that will refresh the pivot table every time the file is opened.

This Microsoft documentation says :

In the PivotTable Options dialog box, on the Data tab, select the Refresh data when opening the file check box.



回答2:

It is possible. In the PivotCacheDefinition, there is an attribute refreshOnLoad that can be set to true. The cache is then refreshed when the workbook is opened. More information here.

In POI this can be done by calling the method setRefreshOnLoad(boolean bool), that takes a boolean as parameter, on a CTPivotCacheDefinition.

EDIT: The Apache POI now provides the possibility to create pivot tables and the pivot table is refreshed on load as default. Class XSSFPivotTable



回答3:

This post says you can turn on an option on the pivot table that will cause it to refresh itself automatically every time the workbook is opened:

How can I refresh all the pivot tables in my excel workbook with a macro?

Hopefully this will still be true after you have used Apache POI to refresh or extend the data rows on which the pivot tables are based.



回答4:

The basic answer to this is no. POI is a document format reader and writer. Updating the Pivot table is an excel engine issue. Sure, another application could try to duplicate the Excel engine behavior here, but that is really going to get ugly. I recommend using Joel's workaround of accessing the excel COM objects over a webservice to get this kind of thing done.



回答5:

This might work:

XSSFPivotTable pivotTable = pivotSheet.getPivotTables().get(0);     
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().setRefreshOnLoad(true);