// Generates content of pivotTableCacheDefinitionPart private static void GeneratePivotTableCacheDefinitionPartContent( PivotTableCacheDefinitionPart pivotTableCacheDefinitionPart, IXLPivotTable pt) { var source = pt.SourceRange; var pivotCacheDefinition = new PivotCacheDefinition { Id = "rId1", SaveData = pt.SaveSourceData, RefreshOnLoad = true //pt.RefreshDataOnOpen }; if (pt.ItemsToRetainPerField == XLItemsToRetain.None) pivotCacheDefinition.MissingItemsLimit = 0U; else if (pt.ItemsToRetainPerField == XLItemsToRetain.Max) pivotCacheDefinition.MissingItemsLimit = XLHelper.MaxRowNumber; pivotCacheDefinition.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"); var cacheSource = new CacheSource {Type = SourceValues.Worksheet}; cacheSource.AppendChild(new WorksheetSource {Name = source.ToString()}); var cacheFields = new CacheFields(); foreach (var c in source.Columns()) { var columnNumber = c.ColumnNumber(); var columnName = c.FirstCell().Value.ToString(); var xlpf = pt.Fields.Add(columnName); var field = pt.RowLabels.Union(pt.ColumnLabels).Union(pt.ReportFilters).FirstOrDefault(f => f.SourceName == columnName); if (field != null) { xlpf.CustomName = field.CustomName; xlpf.Subtotals.AddRange(field.Subtotals); } var sharedItems = new SharedItems(); var onlyNumbers = !source.Cells().Any( cell => cell.Address.ColumnNumber == columnNumber && cell.Address.RowNumber > source.FirstRow().RowNumber() && cell.DataType != XLCellValues.Number); if (onlyNumbers) { sharedItems = new SharedItems {ContainsSemiMixedTypes = false, ContainsString = false, ContainsNumber = true}; } else { foreach (var cellValue in source.Cells().Where(cell => cell.Address.ColumnNumber == columnNumber && cell.Address.RowNumber > source.FirstRow().RowNumber()).Select( cell => cell.Value.ToString()) .Where(cellValue => !xlpf.SharedStrings.Contains(cellValue))) { xlpf.SharedStrings.Add(cellValue); } foreach (var li in xlpf.SharedStrings) { sharedItems.AppendChild(new StringItem {Val = li}); } } var cacheField = new CacheField {Name = xlpf.SourceName}; cacheField.AppendChild(sharedItems); cacheFields.AppendChild(cacheField); } pivotCacheDefinition.AppendChild(cacheSource); pivotCacheDefinition.AppendChild(cacheFields); pivotTableCacheDefinitionPart.PivotCacheDefinition = pivotCacheDefinition; var pivotTableCacheRecordsPart = pivotTableCacheDefinitionPart.AddNewPart<PivotTableCacheRecordsPart>("rId1"); var pivotCacheRecords = new PivotCacheRecords(); pivotCacheRecords.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"); pivotTableCacheRecordsPart.PivotCacheRecords = pivotCacheRecords; }