使用DocumentFormat.OpenXML刷新工作表中的Excel Pivot表

问题描述

有人知道打开文件后是否有一种方法可以使excel重绘数据透视表吗?

我们需要使用数百万条记录来自动创建数据透视表(因此,我们不能将工作表用作数据透视表源,因为它限于1M行)。当前,我们正在使用Excel Interop,但这需要安装Office。

以下代码将新的PivotCacheRecords添加到现有的数据透视表缓存中。而且几乎可以正常工作。唯一的问题是新记录不是立即可见的。打开excel后,需要通过移动字段,应用过滤器或单击枢纽配置面板中的“更新”按钮来更新枢纽(刷新)。之后,pivot中显示的值正确。

我已经寻找解决方案已有一段时间了,没有excel似乎是不可能的,但是也许有一种方法可以解决这个问题。

using var spreadsheetDocument = SpreadsheetDocument.Open(GetSourceFile(),true);

var worksheetPart = spreadsheetDocument.WorkbookPart.GetPartsOfType<WorksheetPart>().First();
var pivottablePart = worksheetPart.GetPartsOfType<PivottablePart>().First();
var cacheDeFinitionPart = pivottablePart.GetPartsOfType<PivottableCacheDeFinitionPart>().First();
var cacheRecordsPart = cacheDeFinitionPart.GetPartsOfType<PivottableCacheRecordsPart>().First();

//add some records 
var r = cacheRecordsPart.PivotCacheRecords;
r.AppendChild(CreateRecord(0,22));
r.AppendChild(CreateRecord(1,10));
PivotCacheRecord CreateRecord(uint sharedString,int value)
{
    var record = new PivotCacheRecord();
    record.AppendChild(new FieldItem { Val = sharedString });
    record.AppendChild(new NumberItem { Val = value });
    return record;
}
r.Count = UInt32Value.FromUInt32((uint)r.ChildElements.Count);

//Set "Fake" sheet so Refresh always fails and does not override data in pivot cache
//Using External connection to not exiting file also works
cacheDeFinitionPart.PivotCacheDeFinition.CacheSource.WorksheetSource.Sheet = "Fake";

//How to update pivot in worksheet?
//This does not work
cacheDeFinitionPart.PivotCacheDeFinition.RefreshOnLoad = true;

spreadsheetDocument.Save();
spreadsheetDocument.Close();
spreadsheetDocument.dispose();

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...