如何使用OpenXML查找数据透视表的数据源

时间:2011-11-23 09:01:45

标签: c# openxml epplus

我正在使用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?

2 个答案:

答案 0 :(得分:3)

数据透视表为数据存储使用数据缓存以提高性能和性能。抽象的原因。请记住,您可以拥有指向Web服务调用的数据透视表。缓存本身就是存储该引用的内容。对于引用工作簿中其他位置的数据的枢轴,您可以在EPPlus中访问它,如下所示:

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

答案 1 :(得分: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;
    }