问题
I want to refresh pivot table after enter data to data sheet
I read two previous questions [this][1] and [this][2]. there two way to do this
one way is
Right click your pivot table -> pivotTable Options -> Data -> Check Refresh Data when opening File
this is working I want a automated way so I tried in this way
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
workbook = new XSSFWorkbook(inputStream);
XSSFSheet sheet = workbook.getSheet("Summary");
XSSFPivotTable pivotTable = sheet.getPivotTables().get(0);
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().setRefreshOnLoad(true);
I have two pivot tables in this sheet so sheet.getPrivotTable return this 
[Name: /xl/pivotTables/pivotTable1.xml - Content Type: application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml, Name: /xl/pivotTables/pivotTable2.xml - Content Type: application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml]
but sheet.getPivotTables().get(0).getPivotCacheDefinition() return null value.
Is there any way to refresh Pivot table automatically?
回答1:
You are correct, the XSSFPivotTable.getPivotCacheDefinition() does not work properly when XSSFPivotTable was read from an existing *.xlsx file. This is because of the kind how the XSSFPivotTable is got form the file. See XSSFSheet.read: The XSSFPivotTable is read from the related document parts of the sheet. But the XSSFPivotTable has relations of it's own. But those are not read at all.
You could file a bug report to apache poi about this. 
Workaround: The XSSFPivotTable extends POIXMLDocumentPart and so it knows about it's own related document parts where the XSSFPivotCacheDefinition is one of.
Example:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileInputStream;
class ExcelReadPivotTables {
 public static void main(String[] args) throws Exception{
  XSSFWorkbook workbook = (XSSFWorkbook)WorkbookFactory.create(new FileInputStream("ExcelWorkbook.xlsx"));
  XSSFSheet sheet = workbook.getSheet("Summary");
  System.out.println(sheet.getPivotTables());
  if (sheet.getPivotTables().size() > 0) {
   XSSFPivotTable pivotTable = sheet.getPivotTables().get(0); 
   System.out.println(pivotTable);
   XSSFPivotCache pivotCache = pivotTable.getPivotCache();
   System.out.println(pivotCache); // null!
   XSSFPivotCacheDefinition pivotCacheDefinition = pivotTable.getPivotCacheDefinition();
   System.out.println(pivotCacheDefinition); //null!
   for (org.apache.poi.ooxml.POIXMLDocumentPart documentPart : pivotTable.getRelations()) {
    if (documentPart instanceof XSSFPivotCacheDefinition) {
     pivotCacheDefinition = (XSSFPivotCacheDefinition)documentPart;
     System.out.println(pivotCacheDefinition); //not null!
    }
   }
  }
  workbook.close();
 }
}
来源:https://stackoverflow.com/questions/53735734/getpivotcachedefinition-return-null-value-when-refresh-pivot-table-with-apache-p