Pivot caches
A pivot cache holds the source fields and records that PivotTables summarize. This page covers where a cache reads from, how a refresh rebuilds it, and how to build one by hand.
Refresh the cache
cache.setWorksheetSource(source) (Python set_worksheet_source(PivotWorksheetSourceInput(...))) names where the cache reads from, as one of:
range: a sheet-qualified A1 range such as'Sheet1!A1:C3', aSheetRect, or an unqualified range withsheet.name: a defined name or a table of this workbook.
Setting the source reads nothing.
cache.refresh() rebuilds the fields and records from it and writes the report of every pivot on the cache again, as Excel's Refresh does. Pending cells are calculated first, and the cache, the pivots and their report cells change together or not at all.
After a refresh, cache.listFields() reports each field's name and its type flags: containsNumber, containsInteger, containsString, containsBlank, containsDate, containsMixedTypes, containsSemiMixedTypes and containsNonDate (Python contains_number and so on).
refresh() throws:
StatusCode.PreconditionFailedwhen the source does not resolve: no source, an external or non-worksheet source, a missing sheet, name or table, or a#REF!or dynamic name.StatusCode.SecurityResourceLimitwhen (rows − 1) × columns of the source exceeds the record cell limit.
A refresh types dates as Excel does:
- A date filter on a field that is no longer all dates (plain numbers, or a mix) is discarded, and every row shows.
- A date group whose base field is no longer all dates is removed together with its group fields and their axis placements, and a missing or unreadable date-group bound is recomputed to the automatic one.
- When the dates move past the bounds of a group by years or by days in intervals longer than one day, a refresh rebuilds the group's items as grouping does, and the pivot field keeps the items whose label survives, in their order, followed by the new ones.
cache.getWorksheetSource() returns the source with range as a SheetRect, whose sheet is a sheet index, so wb.sheet(range.sheet).name gives the name to show. The record a read returns passes back to setWorksheetSource as is:
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
using wb = formulon.Workbook.createDefault()
const ws = wb.sheet(0)
ws.setValues('A1', [['Region', 'Sales'], ['East', 10], ['West', 30]])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'Sheet1!A1:B3' })
cache.refresh()
const pivot = ws.addPivot({ name: 'SalesSummary', cacheId: cache.cacheId, anchor: 'D1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
const source = cache.getWorksheetSource()
console.log(wb.sheet(source.range.sheet).name, source.range.rect.lastRow) // Sheet1 2
// A source read back passes to setWorksheetSource as is.
const copy = wb.addPivotCache()
copy.setWorksheetSource(source)
copy.refresh()
console.log(copy.getRecordCount()) // 2from formulon import (
PivotAggregation, PivotAxis, PivotDataFieldInput, PivotInput,
PivotWorksheetSourceInput, Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values('A1', [['Region', 'Sales'], ['East', 10], ['West', 30]])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range='Sheet1!A1:B3'))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name='SalesSummary', cache_id=cache.cache_id, anchor='D1'))
pivot.set_field_axis('Region', PivotAxis.ROW)
pivot.add_data_field(PivotDataFieldInput(field_index='Sales', aggregation=PivotAggregation.SUM))
source = cache.get_worksheet_source()
print(wb.sheet(source.range.sheet).name, source.range.rect.last_row) # Sheet1 2
# A source read back passes to set_worksheet_source as is.
copy = wb.add_pivot_cache()
copy.set_worksheet_source(source)
copy.refresh()
print(copy.get_record_count()) # 2wb.formatReference(range) writes the source as A1 text with its sheet name. This example needs an engine release that accepts a SheetRect in formatReference, so it is not run yet.
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
using wb = formulon.Workbook.createDefault()
const ws = wb.sheet(0)
ws.setValues('A1', [['Region', 'Sales'], ['East', 10], ['West', 30]])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'Sheet1!A1:B3' })
cache.refresh()
const pivot = ws.addPivot({ name: 'SalesSummary', cacheId: cache.cacheId, anchor: 'D1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
const source = cache.getWorksheetSource()
// @ts-expect-error
if (source?.range) console.log(wb.formatReference(source.range)) // Sheet1!A1:B3from formulon import (
PivotAggregation, PivotAxis, PivotDataFieldInput, PivotInput,
PivotWorksheetSourceInput, Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values('A1', [['Region', 'Sales'], ['East', 10], ['West', 30]])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range='Sheet1!A1:B3'))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name='SalesSummary', cache_id=cache.cache_id, anchor='D1'))
pivot.set_field_axis('Region', PivotAxis.ROW)
pivot.add_data_field(PivotDataFieldInput(field_index='Sales', aggregation=PivotAggregation.SUM))
print(wb.format_reference(cache.get_worksheet_source().range)) # Sheet1!A1:B3A cache does not follow its source by itself. After the source cells change, the pivot shows the old figures until refresh() runs again. This cache reads from a defined name:
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
using wb = formulon.Workbook.createDefault()
const ws = wb.sheet(0)
ws.setValues('A1', [['Region', 'Sales'], ['East', 10], ['West', 30]])
wb.setDefinedName({ name: 'SalesData', formula: 'Sheet1!$A$1:$B$3' })
const cache = wb.addPivotCache()
cache.setWorksheetSource({ name: 'SalesData' })
cache.refresh()
const pivot = ws.addPivot({ name: 'ByRegion', cacheId: cache.cacheId, anchor: 'D1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
console.log(ws.getValue('E2')) // 10
ws.setValue('B2', 25)
console.log(ws.getValue('E2')) // 10
cache.refresh() // re-reads SalesData and rewrites the report
console.log(ws.getValue('E2')) // 25from formulon import (
DefinedNameInput, PivotAggregation, PivotAxis, PivotDataFieldInput, PivotInput,
PivotWorksheetSourceInput, Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values('A1', [['Region', 'Sales'], ['East', 10], ['West', 30]])
wb.set_defined_name(DefinedNameInput('SalesData', 'Sheet1!$A$1:$B$3'))
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(name='SalesData'))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name='ByRegion', cache_id=cache.cache_id, anchor='D1'))
pivot.set_field_axis('Region', PivotAxis.ROW)
pivot.add_data_field(PivotDataFieldInput(field_index='Sales', aggregation=PivotAggregation.SUM))
print(ws['E2']) # 10.0
ws['B2'] = 25
print(ws['E2']) # 10.0
cache.refresh() # re-reads SalesData and rewrites the report
print(ws['E2']) # 25.0Where the source resolves now
cache.getWorksheetSourceRange() (Python get_worksheet_source_range()) returns the sheet and rectangle the source resolves to now, which is the range refresh() reads: a table's header row through its last data row, without the totals row, a defined name's current range, or the range as written.
It returns null when the source does not resolve: no source, a source of another kind or in another workbook, a table or name that is missing or does not name one rectangle on one sheet, or a missing sheet. A deleted table or name leaves the source as that name, so getWorksheetSource().name still reports it while this call returns null.
Deleting the sheet a cache reads keeps the cache, its records and every pivot on it, as Excel does. The source still names the deleted sheet, and refresh() fails with StatusCode.PreconditionFailed.
Formats after a refresh
Cell formats and pivot chart formats that a loaded PivotTable carries follow the items and value fields they name, as Excel's do.
- After a refresh a format moves with its item to the item's new position.
- A format on an item the refresh removes (
missingItemsLimit0) or on a field whose source column is gone is removed; one on an item kept as missing stays. - Removing a value field, by refresh, by deleting a calculated field or by taking it out of the values area, removes the formats on it and moves the formats of later value fields down.
- Removing a grouping removes the formats on its group fields, and for a numeric grouping those on the field itself.
pivot.clearFields()removes every cell format and leaves the chart formats.
Refresh on open
A cache whose refreshOnLoad option (cache.getOptions()) is on in an opened .xlsx or .xlsb is refreshed from its source before the workbook is first read, edited, calculated or saved, as Excel refreshes it on open.
A profile set right after the load (setProfileId, Python set_profile_id) applies first, so blank-header field names and date-group labels follow it. A cache whose refresh fails, for example because its source sheet is gone, keeps the records the file stored.
A cache built through the API is saved with refreshOnLoad on unless a refresh filled its records, so the reopened book shows what its source holds rather than records written by hand.
Build a cache by hand
A cache can also be filled without a worksheet range: cache.addField(name) adds a field, cache.addRecord() a record, and cache.setRecordValue(record, field, value) (Python set_record_value) writes one cell, picking the typed writer from the type of value (number, string, boolean, null, Date or an ErrorValue). A Date is stored as a date and a number as a number; Python takes date and datetime the same way.
cache.addFieldSharedItem(field, value) works the same way for shared items. listFieldSharedItems() entries carry isDate (Python is_date), and the value of a date item is its serial. A cache built by hand still needs a worksheet source before a pivot that uses it can be saved.
A value the field already holds is refused with StatusCode.AlreadyExists (Python AlreadyExistsError):
import createFormulon, { FormulonError, StatusCode } from '@libraz/formulon'
const formulon = await createFormulon()
using wb = formulon.Workbook.createDefault()
const cache = wb.addPivotCache()
cache.addField('Region')
console.log(cache.addFieldSharedItem(0, 'East')) // 0
try {
cache.addFieldSharedItem(0, 'East')
} catch (e) {
if (!(e instanceof FormulonError)) throw e
console.log(formulon.enumName(StatusCode, e.code)) // AlreadyExists
}from formulon import AlreadyExistsError, Workbook
with Workbook.create_default() as wb:
cache = wb.add_pivot_cache()
cache.add_field("Region")
print(cache.add_field_shared_item(0, "East")) # 0
try:
cache.add_field_shared_item(0, "East")
except AlreadyExistsError as e:
print(e.code.name) # ALREADY_EXISTSThe example below builds a cache with its shared items listed explicitly and hides the blank member through the item bound to its index.
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
using wb = formulon.Workbook.createDefault()
const ws = wb.sheet(0)
const rows = [['Region', 'Sales'], ['East', 10], ['West', 30], [null, 5]]
ws.setValues('A1', rows)
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'Sheet1!A1:B4' })
for (const name of rows[0]) cache.addField(name)
for (const item of ['East', 'West', null]) cache.addFieldSharedItem(0, item) // index 2 is the blank
for (const row of rows.slice(1)) {
const record = cache.addRecord()
row.forEach((value, field) => cache.setRecordValue(record, field, value))
}
const pivot = ws.addPivot({ name: 'SalesSummary', cacheId: cache.cacheId, anchor: 'D1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
const labels = () => pivot.getLayout().cells.map((cell) => cell.value).join(' | ')
const before = labels()
// Region is on an axis, so it lists its items; find the one bound to shared item 2.
const blank = pivot.listFieldItems(0).findIndex((item) => item.cacheIndex === 2)
pivot.updateFieldItem(/*fieldIndex*/ 0, blank, { visible: false })
console.log(before)
console.log(labels())
// Row Labels | Sum of Sales | East | 10 | West | 30 | (blank) | 5 | Grand Total | 45
// Row Labels | Sum of Sales | East | 10 | West | 30 | Grand Total | 40from formulon import (
PivotAggregation, PivotAxis, PivotDataFieldInput, PivotInput,
PivotWorksheetSourceInput, Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
rows = [['Region', 'Sales'], ['East', 10], ['West', 30], [None, 5]]
ws.set_values('A1', rows)
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range='Sheet1!A1:B4'))
for name in rows[0]:
cache.add_field(name)
for item in ('East', 'West', None):
cache.add_field_shared_item(0, item) # index 2 is the blank
for row in rows[1:]:
record = cache.add_record()
for field, value in enumerate(row):
cache.set_record_value(record, field, value)
pivot = ws.add_pivot(PivotInput(name='SalesSummary', cache_id=cache.cache_id, anchor='D1'))
pivot.set_field_axis('Region', PivotAxis.ROW)
pivot.add_data_field(PivotDataFieldInput(field_index='Sales', aggregation=PivotAggregation.SUM))
def labels():
return ' | '.join(str(cell.value) for cell in pivot.get_layout().cells)
before = labels()
# Region is on an axis, so it lists its items; find the one bound to shared item 2.
blank = next(i for i, item in enumerate(pivot.list_field_items(0)) if item.cache_index == 2)
pivot.update_field_item(0, blank, visible=False) # field_index=0
print(before)
print(labels())
# Row Labels | Sum of Sales | East | 10.0 | West | 30.0 | (blank) | 5.0 | Grand Total | 45.0
# Row Labels | Sum of Sales | East | 10.0 | West | 30.0 | Grand Total | 40.0Address a cache item by index
A field placed on an axis lists its items at once, in display order, and each item carries the cacheIndex of its shared item. pivot.updateFieldItem(field, item, { visible }) (Python update_field_item(field, item, visible=...)) hides or shows one of them, where item is its position in listFieldItems(field); this is how the blank member is reached, because an empty label is text matching and cannot identify it.
pivot.addFieldItem(field, { cacheIndex }) / add_field_item(field, cache_index=...) binds a manual-filter item to a shared-item index the field does not list yet, and fails with StatusCode.AlreadyExists (Python AlreadyExistsError) for one it lists. The index is the same zero-based space as the OOXML pivot item x attribute. Populate the cache before evaluating the pivot when the item must match records.
After refresh(), a field that joins an axis gets shared items and listFieldSharedItems gives the index of each one; a field on no axis has none. An index that does not resolve is accepted when it is added and filters nothing, and the item is left out when the workbook is saved:
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
using wb = formulon.Workbook.createDefault()
const ws = wb.sheet(0)
ws.setValues('A1', [['Region', 'Sales'], ['East', 10], ['West', 30], [null, 5]])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'Sheet1!A1:B4' })
cache.refresh()
const pivot = ws.addPivot({ name: 'SalesSummary', cacheId: cache.cacheId, anchor: 'D1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
// Region is on an axis, so it has shared items.
const items = cache.listFieldSharedItems(0).map((item) => item.value)
console.log(items) // [ 'East', 'West', null ]
const blank = pivot.listFieldItems(0).findIndex((item) => item.cacheIndex === items.indexOf(null))
pivot.updateFieldItem(/*fieldIndex*/ 0, blank, { visible: false })
console.log(JSON.stringify(ws.getValues('D1:E4')))
// There is no shared item 9: the item is accepted, and left out on save.
pivot.addFieldItem(0, { cacheIndex: 9 }, { visible: false })
const listsNine = (p) => p.listFieldItems(0).some((item) => item.cacheIndex === 9)
using reloaded = formulon.Workbook.load(wb.save())
console.log(listsNine(pivot), listsNine(reloaded.sheet(0).pivot(0)))
// [["Row Labels","Sum of Sales"],["East",10],["West",30],["Grand Total",40]]
// true falsefrom formulon import (
PivotAggregation, PivotAxis, PivotDataFieldInput, PivotInput,
PivotWorksheetSourceInput, Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values('A1', [['Region', 'Sales'], ['East', 10], ['West', 30], [None, 5]])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range='Sheet1!A1:B4'))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name='SalesSummary', cache_id=cache.cache_id, anchor='D1'))
pivot.set_field_axis('Region', PivotAxis.ROW)
pivot.add_data_field(PivotDataFieldInput(field_index='Sales', aggregation=PivotAggregation.SUM))
# Region is on an axis, so it has shared items.
items = [item.value for item in cache.list_field_shared_items(0)]
print(items) # ['East', 'West', None]
blank = next(i for i, item in enumerate(pivot.list_field_items(0)) if item.cache_index == items.index(None))
pivot.update_field_item(0, blank, visible=False) # field_index=0
print(ws.get_values('D1:E4'))
# There is no shared item 9: the item is accepted, and left out on save.
pivot.add_field_item(0, cache_index=9, visible=False)
data = wb.save()
in_session = any(item.cache_index == 9 for item in pivot.list_field_items(0))
with Workbook.load(data) as reloaded:
print(in_session, any(item.cache_index == 9 for item in reloaded[0].pivot(0).list_field_items(0)))
# [['Row Labels', 'Sum of Sales'], ['East', 10.0], ['West', 30.0], ['Grand Total', 40.0]]
# True FalsePivot cache sources
Newly authored PivotTables must set a worksheet source on their cache before saving. Use cache.setWorksheetSource({ range: 'A1:C10', sheet: 'Data' }) on the PivotCache handle in JavaScript, or cache.set_worksheet_source(PivotWorksheetSourceInput(range='A1:C10', sheet='Data')) in Python (sheet qualifies an unqualified range; a qualified range whose sheet disagrees fails with StatusCode.InvalidArgument); setWorksheetSource(null) (Python set_worksheet_source(None)) clears it.
getWorksheetSource() returns null when the cache has none, and otherwise the source with range as a SheetRect (null when the source has no reference or names a missing sheet) and the name. A declared range is enough even when the sheet has no data.
Saving fails while a pivot uses a newly created cache that has no worksheet source; a cache no pivot uses is left out of the saved file. A loaded cache retains its supported source metadata, which may describe a non-worksheet or external source; the requirement here applies to newly authored worksheet caches.