![](/img/trans.png)
[英]If pivot table/range is added to Data Model, how to get the the source of pivot table in C#?
[英]How to find the data source of a Pivot Table using OpenXML
我正在使用EPP打開和編輯現有的Excel文檔。
該文件包含2張紙 - 一張帶有一個數據透視表(名為Pivot),另一張帶有數據(Data!$A$1:$L$9899)
。
我使用下面的代碼對ExcelPivotTable進行了引用,但是找不到與數據源相關的任何屬性。
ExcelPackage package = new ExcelPackage(pivotSpreadsheet);
foreach (ExcelWorksheet worksheet in package.Workbook.Worksheets)
{
if (worksheet.PivotTables.Count > 0)
{
pivotWorkSheetName = worksheet.Name;
pivotTable = worksheet.PivotTables[0];
}
}
如何獲得源數據的名稱和范圍? 我是否缺少明顯的屬性,還是必須通過一些xml尋找屬性?
由於性能和抽象原因,數據透視表為數據存儲使用數據高速緩存。 請記住,您可以有一個指向Web服務調用的樞軸。 緩存本身就是存儲該引用的內容。 對於引用工作簿中其他位置的數據的樞軸,您可以在EPPlus中訪問它,如下所示:
worksheet.PivotTables[0].CacheDefinition.SourceRange.FullAddress;
如果有人有興趣使用OpenXML SDK 2.5更新數據源,那么這里是我使用的代碼。
using (var spreadsheet = SpreadsheetDocument.Open(filepath, true))
{
PivotTableCacheDefinitionPart ptp = spreadsheet.WorkbookPart.PivotTableCacheDefinitionParts.First();
ptp.PivotCacheDefinition.RefreshOnLoad = true;//refresh the pivot table on document load
ptp.PivotCacheDefinition.RecordCount = Convert.ToUInt32(ds.Tables[0].Rows.Count);
ptp.PivotCacheDefinition.CacheSource.WorksheetSource.Reference = "A1:" + IntToLetters(ds.Tables[0].Columns.Count) + (ds.Tables[0].Rows.Count + 1);//Cell Range as data source
ptp.PivotTableCacheRecordsPart.PivotCacheRecords.RemoveAllChildren();//it is rebuilt when pivot table is refreshed
ptp.PivotTableCacheRecordsPart.PivotCacheRecords.Count = 0;//it is rebuilt when pivot table is refreshed
}
public string IntToLetters(int value)//copied from another stackoverflow post
{
string result = string.Empty;
while (--value >= 0)
{
result = (char)('A' + value % 26) + result;
value /= 26;
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.