2011-11-23 77 views
1

我正在使用EPP打开和编辑现有的Excel文档。如何使用OpenXML查找数据透视表的数据源

该文件包含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寻找?

回答

3

数据透视表使用数据存储的数据缓存以获得性能&抽象原因。请记住,您可以拥有一个指向Web服务调用的数据透视表。缓存本身就是存储该参考的内容。对于指数据在其他地方工作簿中的支点,您可以访问它在EPPlus这样的:

worksheet.PivotTables[0].CacheDefinition.SourceRange.FullAddress; 
+0

感谢 - 这正是我一直在寻找 – woggles

+0

任何想法如何更新此值(我更新的数据源,并需要更新数据透视表中引用)? – geedubb

0

如果有人有兴趣与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; 
    }