java - 使用 Apache POI 刷新数据透视表时 getPivotCacheDefinition 返回 null 值

标签 java excel apache-poi pivot-table

我想在将数据输入数据表后刷新数据透视表

我阅读了之前的两个问题 [this][1] 和 [this][2]。有两种方法可以做到这一点

一种方法是

右键单击数据透视表 -> 数据透视表选项 -> 数据 -> 打开文件时选中刷新数据

这是可行的,我想要一种自动化的方式,所以我尝试了这种方式

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

我在此工作表中有两个数据透视表,因此 sheet.getPrivotTable 返回此

[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]

但是sheet.getPivotTables().get(0).getPivotCacheDefinition()返回空值。

有没有办法自动刷新数据透视表?

最佳答案

您是对的,从现有 *.xlsx 文件读取 XSSFPivotTable 时,XSSFPivotTable.getPivotCacheDefinition() 无法正常工作。这是因为 XSSFPivotTable 从文件中获取的方式不同。请参阅XSSFSheet.read :XSSFPivotTable 是从工作表的相关文档部分读取的。但XSSFPivotTable 有它自己的关系。但这些根本没有被阅读。

您可以向 apache poi 提交有关此问题的错误报告。

解决方法:XSSFPivotTable 扩展了 POIXMLDocumentPart,因此它知道 XSSFPivotCacheDefinition 是其自己的相关文档部分之一。

示例:

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

关于java - 使用 Apache POI 刷新数据透视表时 getPivotCacheDefinition 返回 null 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53735734/

相关文章:

java - 为什么 Apache Camel 拦截不起作用?

excel - VBA函数=函数参数?

excel - 替代单元格在excel中的自动增量?

java - 自定义 Gradle 任务类使用哪种语言?

java - 将线分割(分割)成任意长度的段。 (开始时短,结束时宽)

java - 关于java Sockets的愚蠢问题:can i make a client listener on the input stream while the client writes the first thing to the object?

excel - 如何根据文档中的值更新 SharePoint 内容类型属性?

java - 无法打开超链接文件 Apache POI

java - 使用 POI 在 docx 文件中另一个表的单元格中添加表

java - 在 Apache POI 中设置样式