Build a PivotTable
Use this page to summarise rows on a sheet into a PivotTable that Excel can open and refresh, to read the report back, and to bring it up to date when the rows change. Configure PivotTable fields lists every pivot option, and the WASM API and Python API list the calls.
Build a cache from a sheet range
A pivot reads from a pivot cache, not from the sheet. setWorksheetSource names the range the cache comes from, a range on a sheet or a defined name, and refresh() reads it the way Excel's Refresh does: the header row becomes the cache fields and every row below it becomes a record.
import createFormulon from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [
['Region', 'Product', 'Sales'],
['East', 'Widget', 10],
['West', 'Gadget', 30],
['East', 'Gadget', 5],
['West', 'Widget', 20],
])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'A1:C5', sheet: 'Sheet1' })
cache.refresh()
console.log(cache.getRecordCount()) // 4
console.log(cache.listFields().map((f) => f.name).join()) // Region,Product,Sales
console.log(cache.getRecordValue(1, 'Sales').value) // 30
const source = cache.getWorksheetSource()
console.log(wb.sheet(source.range.sheet).name, JSON.stringify(source.range.rect)) // Sheet1 {"firstRow":0,"firstCol":0,"lastRow":4,"lastCol":2}
cache.setWorksheetSource(source)
} finally {
wb.dispose()
}from formulon import PivotWorksheetSourceInput, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [
["Region", "Product", "Sales"],
["East", "Widget", 10],
["West", "Gadget", 30],
["East", "Gadget", 5],
["West", "Widget", 20],
])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range="A1:C5", sheet="Sheet1"))
cache.refresh()
print(cache.get_record_count()) # 4
print(",".join(f.name for f in cache.list_fields())) # Region,Product,Sales
print(cache.get_record_value(1, "Sales").value) # 30.0
source = cache.get_worksheet_source()
print(wb.sheet(source.range.sheet).name, source.range.rect) # Sheet1 CellRect(first_row=0, first_col=0, last_row=4, last_col=2)
cache.set_worksheet_source(source)getWorksheetSource() returns the source with the sheet as an index (range.sheet) and the cells as a CellRect, and the record it returns passes back to setWorksheetSource unchanged. A source given by defined name reads back with name set and range null. refresh() fails with StatusCode.PreconditionFailed when the cache has no source or the source does not resolve.
Create the pivot and place fields
ws.addPivot creates the pivot at anchor. It starts with one field per cache field and none of them on an axis. setFieldAxis(field, axis) places a field on rows, columns, the page (filter) area or values, and null takes it off again. A field is named by its cache field name or its position. Each field placed on rows or columns is appended to that axis's order, which getRowFieldOrder() and getColumnFieldOrder() read as cache field positions.
import createFormulon, { PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [
['Region', 'Product', 'Sales'],
['East', 'Widget', 10],
['West', 'Gadget', 30],
['East', 'Gadget', 5],
['West', 'Widget', 20],
])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'A1:C5', sheet: 'Sheet1' })
cache.refresh()
const pivot = ws.addPivot({ name: 'SalesByRegion', cacheId: cache.cacheId, anchor: 'E1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.setFieldAxis('Product', PivotAxis.Column)
pivot.setFieldAxis('Sales', PivotAxis.Value)
console.log(JSON.stringify(pivot.getRowFieldOrder())) // [0]
console.log(JSON.stringify(pivot.getColumnFieldOrder())) // [1]
console.log(pivot.getField('Sales').axis === PivotAxis.Value) // true
} finally {
wb.dispose()
}from formulon import PivotAxis, PivotInput, PivotWorksheetSourceInput, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [
["Region", "Product", "Sales"],
["East", "Widget", 10],
["West", "Gadget", 30],
["East", "Gadget", 5],
["West", "Widget", 20],
])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range="A1:C5", sheet="Sheet1"))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name="SalesByRegion", cache_id=cache.cache_id, anchor="E1"))
pivot.set_field_axis("Region", PivotAxis.ROW)
pivot.set_field_axis("Product", PivotAxis.COLUMN)
pivot.set_field_axis("Sales", PivotAxis.VALUE)
print(pivot.get_row_field_order()) # [0]
print(pivot.get_column_field_order()) # [1]
print(pivot.get_field("Sales").axis == PivotAxis.VALUE) # TrueA field on the values axis shows nothing until a data field aggregates it, which is the next step.
Add a data field and read the report
addDataField adds an aggregation of one field. Without a name, the data field is named in the profile's wording, Sum of Sales under an English profile. The engine writes the report into the sheet cells from the anchor, so getValues reads it like any other range. setRowFieldOrder and setColumnFieldOrder replace an axis's whole membership, so swapping the two lists turns the report around.
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [
['Region', 'Product', 'Sales'],
['East', 'Widget', 10],
['West', 'Gadget', 30],
['East', 'Gadget', 5],
['West', 'Widget', 20],
])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'A1:C5', sheet: 'Sheet1' })
cache.refresh()
const pivot = ws.addPivot({ name: 'SalesByRegion', cacheId: cache.cacheId, anchor: 'E1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.setFieldAxis('Product', PivotAxis.Column)
pivot.setFieldAxis('Sales', PivotAxis.Value)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
console.log(pivot.listDataFields()[0].name) // Sum of Sales
let report = ws.getValues('E1:H5')
console.log(JSON.stringify(report[1])) // ["Row Labels","Gadget","Widget","Grand Total"]
console.log(JSON.stringify(report[2])) // ["East",5,10,15]
console.log(JSON.stringify(report[4])) // ["Grand Total",35,30,65]
pivot.setRowFieldOrder(['Product'])
pivot.setColumnFieldOrder(['Region'])
report = ws.getValues('E1:H5')
console.log(JSON.stringify(report[1])) // ["Row Labels","East","West","Grand Total"]
console.log(JSON.stringify(report[2])) // ["Gadget",5,30,35]
} finally {
wb.dispose()
}from formulon import (
PivotAggregation,
PivotAxis,
PivotDataFieldInput,
PivotInput,
PivotWorksheetSourceInput,
Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [
["Region", "Product", "Sales"],
["East", "Widget", 10],
["West", "Gadget", 30],
["East", "Gadget", 5],
["West", "Widget", 20],
])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range="A1:C5", sheet="Sheet1"))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name="SalesByRegion", cache_id=cache.cache_id, anchor="E1"))
pivot.set_field_axis("Region", PivotAxis.ROW)
pivot.set_field_axis("Product", PivotAxis.COLUMN)
pivot.set_field_axis("Sales", PivotAxis.VALUE)
pivot.add_data_field(PivotDataFieldInput(field_index="Sales", aggregation=PivotAggregation.SUM))
print(pivot.list_data_fields()[0].name) # Sum of Sales
report = ws["E1:H5"]
print(report[1]) # ['Row Labels', 'Gadget', 'Widget', 'Grand Total']
print(report[2]) # ['East', 5.0, 10.0, 15.0]
print(report[4]) # ['Grand Total', 35.0, 30.0, 65.0]
pivot.set_row_field_order(["Product"])
pivot.set_column_field_order(["Region"])
report = ws["E1:H5"]
print(report[1]) # ['Row Labels', 'East', 'West', 'Grand Total']
print(report[2]) # ['Gadget', 5.0, 30.0, 35.0]PivotAggregation also has Count, Average, Max, Min and the other Excel summary functions, and showAs on the data field selects a Show Values As mode. With two fields on the row axis, the list order is the nesting order, outermost first.
Refresh after the source data changes
The cache keeps its own copy of the records, so an edit to the source cells does not change the pivot by itself. cache.refresh() reads the source range again, as Excel's Refresh does, and every pivot on the cache shows the new figures. A GETPIVOTDATA formula that reads the pivot returns the new value at the next calculation. Rows added below the range are outside it; widen the range with setWorksheetSource, or point the source at a defined name or a table that grows with the data.
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [
['Region', 'Product', 'Sales'],
['East', 'Widget', 10],
['West', 'Gadget', 30],
['East', 'Gadget', 5],
['West', 'Widget', 20],
])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'A1:C5', sheet: 'Sheet1' })
cache.refresh()
const pivot = ws.addPivot({ name: 'SalesByRegion', cacheId: cache.cacheId, anchor: 'E1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.setFieldAxis('Sales', PivotAxis.Value)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
ws.setFormula('H1', '=GETPIVOTDATA("Sales",E1,"Region","East")')
ws.setValue('C2', 100)
console.log(ws.getValue('F2'), ws.getValue('H1')) // 15 15
cache.refresh()
console.log(ws.getValue('F2'), ws.getValue('H1')) // 105 105
} finally {
wb.dispose()
}from formulon import (
PivotAggregation,
PivotAxis,
PivotDataFieldInput,
PivotInput,
PivotWorksheetSourceInput,
Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [
["Region", "Product", "Sales"],
["East", "Widget", 10],
["West", "Gadget", 30],
["East", "Gadget", 5],
["West", "Widget", 20],
])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range="A1:C5", sheet="Sheet1"))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name="SalesByRegion", cache_id=cache.cache_id, anchor="E1"))
pivot.set_field_axis("Region", PivotAxis.ROW)
pivot.set_field_axis("Sales", PivotAxis.VALUE)
pivot.add_data_field(PivotDataFieldInput(field_index="Sales", aggregation=PivotAggregation.SUM))
ws.set_formula("H1", '=GETPIVOTDATA("Sales",E1,"Region","East")')
ws["C2"] = 100
print(ws["F2"], ws["H1"]) # 15.0 15.0
cache.refresh()
print(ws["F2"], ws["H1"]) # 105.0 105.0Save and reopen
save() writes the pivot definition, its cache and the projected cells. Excel opens the file with the report in place and refreshes it from the same source range. A loaded workbook gives back the pivot through ws.listPivots() or ws.pivot(name), and its cache can be refreshed again.
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
let bytes
try {
const ws = wb.sheet(0)
ws.setValues('A1', [
['Region', 'Product', 'Sales'],
['East', 'Widget', 10],
['West', 'Gadget', 30],
['East', 'Gadget', 5],
['West', 'Widget', 20],
])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'A1:C5', sheet: 'Sheet1' })
cache.refresh()
const pivot = ws.addPivot({ name: 'SalesByRegion', cacheId: cache.cacheId, anchor: 'E1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.setFieldAxis('Sales', PivotAxis.Value)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
bytes = wb.save()
} finally {
wb.dispose()
}
const back = formulon.Workbook.load(bytes)
try {
const ws = back.sheet(0)
const pivot = ws.pivot('SalesByRegion')
console.log(pivot.listDataFields()[0].name) // Sum of Sales
ws.setValue('C3', 50)
pivot.cache().refresh()
console.log(JSON.stringify(ws.getValues('E4:F4'))) // [["Grand Total",85]]
} finally {
back.dispose()
}from formulon import (
PivotAggregation,
PivotAxis,
PivotDataFieldInput,
PivotInput,
PivotWorksheetSourceInput,
Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [
["Region", "Product", "Sales"],
["East", "Widget", 10],
["West", "Gadget", 30],
["East", "Gadget", 5],
["West", "Widget", 20],
])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range="A1:C5", sheet="Sheet1"))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name="SalesByRegion", cache_id=cache.cache_id, anchor="E1"))
pivot.set_field_axis("Region", PivotAxis.ROW)
pivot.set_field_axis("Sales", PivotAxis.VALUE)
pivot.add_data_field(PivotDataFieldInput(field_index="Sales", aggregation=PivotAggregation.SUM))
wb.save("pivot.xlsx")
with Workbook.load("pivot.xlsx") as back:
ws = back[0]
pivot = ws.pivot("SalesByRegion")
print(pivot.list_data_fields()[0].name) # Sum of Sales
ws["C3"] = 50
pivot.cache().refresh()
print(ws["E4:F4"]) # [['Grand Total', 85.0]]Fill a cache from records
A cache can also hold data that is not on any sheet, such as rows from a database. Add one field per column with addField and one record per row with addRecord and setRecordValue, which takes a field by position or by name. A record change marks every pivot on the cache as pending (isProjectionPending()), and pivot.project() writes the report again. To save such a pivot the cache still needs a worksheet source, because Excel refreshes from it; save() fails without one.
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
const cache = wb.addPivotCache()
for (const name of ['Region', 'Product', 'Sales']) cache.addField(name)
for (const row of [['East', 'Widget', 10], ['West', 'Gadget', 30], ['East', 'Gadget', 5], ['West', 'Widget', 20]]) {
const record = cache.addRecord()
row.forEach((value, field) => cache.setRecordValue(record, field, value))
}
const pivot = ws.addPivot({ name: 'SalesByRegion', cacheId: cache.cacheId, anchor: 'A1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.setFieldAxis('Sales', PivotAxis.Value)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
console.log(JSON.stringify(ws.getValues('A2:B3'))) // [["East",15],["West",50]]
cache.setRecordValue(0, 'Sales', 100)
console.log(pivot.isProjectionPending(), ws.getValue('B2')) // true 15
pivot.project()
console.log(pivot.isProjectionPending(), ws.getValue('B2')) // false 105
} finally {
wb.dispose()
}from formulon import PivotAggregation, PivotAxis, PivotDataFieldInput, PivotInput, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
cache = wb.add_pivot_cache()
for name in ("Region", "Product", "Sales"):
cache.add_field(name)
for row in [["East", "Widget", 10], ["West", "Gadget", 30], ["East", "Gadget", 5], ["West", "Widget", 20]]:
record = cache.add_record()
for field, value in enumerate(row):
cache.set_record_value(record, field, value)
pivot = ws.add_pivot(PivotInput(name="SalesByRegion", cache_id=cache.cache_id, anchor="A1"))
pivot.set_field_axis("Region", PivotAxis.ROW)
pivot.set_field_axis("Sales", PivotAxis.VALUE)
pivot.add_data_field(PivotDataFieldInput(field_index="Sales", aggregation=PivotAggregation.SUM))
print(ws["A2:B3"]) # [['East', 15.0], ['West', 50.0]]
cache.set_record_value(0, "Sales", 100)
print(pivot.is_projection_pending(), ws["B2"]) # True 15.0
pivot.project()
print(pivot.is_projection_pending(), ws["B2"]) # False 105.0Read the layout for rendering
pivot.getLayout() returns the report as a list of cells, each with its sheet position, value, kind (PivotCellKind: header, row label, column label, data, subtotal, grand total, blank), outline depth, field name, number format and expansion (PivotCellExpansion), the state of the expand / collapse button on an item label, or null where there is no button. A host that draws its own pivot uses it to style labels and totals differently and to draw the buttons. getLayout() computes the report from the cache records and writes nothing to the sheet.
import createFormulon, { PivotAggregation, PivotAxis, PivotCellKind } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
const cache = wb.addPivotCache()
for (const name of ['Region', 'Product', 'Sales']) cache.addField(name)
for (const row of [['East', 'Widget', 10], ['West', 'Gadget', 30], ['East', 'Gadget', 5], ['West', 'Widget', 20]]) {
const record = cache.addRecord()
row.forEach((value, field) => cache.setRecordValue(record, field, value))
}
const pivot = ws.addPivot({ name: 'SalesByRegion', cacheId: cache.cacheId, anchor: 'E1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.setFieldAxis('Sales', PivotAxis.Value)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
const layout = pivot.getLayout()
console.log(JSON.stringify(layout.range)) // {"firstRow":0,"firstCol":4,"lastRow":3,"lastCol":5}
const labels = layout.cells.filter((c) => c.kind === PivotCellKind.RowLabel)
console.log(labels.map((c) => `${c.value}@${c.row},${c.col}`).join(' ')) // East@1,4 West@2,4
const data = layout.cells.filter((c) => c.kind === PivotCellKind.Data)
console.log(data.map((c) => c.value).join()) // 15,50
} finally {
wb.dispose()
}from formulon import (
PivotAggregation,
PivotAxis,
PivotCellKind,
PivotDataFieldInput,
PivotInput,
Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
cache = wb.add_pivot_cache()
for name in ("Region", "Product", "Sales"):
cache.add_field(name)
for row in [["East", "Widget", 10], ["West", "Gadget", 30], ["East", "Gadget", 5], ["West", "Widget", 20]]:
record = cache.add_record()
for field, value in enumerate(row):
cache.set_record_value(record, field, value)
pivot = ws.add_pivot(PivotInput(name="SalesByRegion", cache_id=cache.cache_id, anchor="E1"))
pivot.set_field_axis("Region", PivotAxis.ROW)
pivot.set_field_axis("Sales", PivotAxis.VALUE)
pivot.add_data_field(PivotDataFieldInput(field_index="Sales", aggregation=PivotAggregation.SUM))
layout = pivot.get_layout()
r = layout.range
print(r.first_row, r.first_col, r.last_row, r.last_col) # 0 4 3 5
labels = [c for c in layout.cells if c.kind == PivotCellKind.ROW_LABEL]
print(" ".join(f"{c.value}@{c.row},{c.col}" for c in labels)) # East@1,4 West@2,4
data = [c for c in layout.cells if c.kind == PivotCellKind.DATA]
print([c.value for c in data]) # [15.0, 50.0]Change the row field, column field and aggregation to see the cells getLayout() returns.
PivotTable projection
The same rows as the source table go into a pivot cache. Each change of row field, column field or aggregation rebuilds the pivot and renders the result of getLayout().
Powered by the real Formulon engine (WASM) — it runs entirely in your browser, nothing is uploaded.
Sort, rename and query the pivot
updateField(field, patch) changes a field's sort order, subtotals, number format and other properties, and the report is projected again at once. rename changes the pivot's name. GETPIVOTDATA reads a figure from the report by field and item, and takes the data field by its source name (Sales) or its own name (Sum of Sales).
import createFormulon, { PivotAggregation, PivotAxis, PivotSortOrder } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
const cache = wb.addPivotCache()
for (const name of ['Region', 'Product', 'Sales']) cache.addField(name)
for (const row of [['East', 'Widget', 10], ['West', 'Gadget', 30], ['East', 'Gadget', 5], ['West', 'Widget', 20]]) {
const record = cache.addRecord()
row.forEach((value, field) => cache.setRecordValue(record, field, value))
}
const pivot = ws.addPivot({ name: 'SalesByRegion', cacheId: cache.cacheId, anchor: 'A1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.setFieldAxis('Sales', PivotAxis.Value)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
pivot.updateField('Region', { sortOrder: PivotSortOrder.Descending })
pivot.rename('Sales by region')
console.log(JSON.stringify(ws.getValues('A2:B3'))) // [["West",50],["East",15]]
console.log(ws.listPivots().map((p) => p.name).join()) // Sales by region
ws.setFormula('E1', '=GETPIVOTDATA("Sales",A1,"Region","East")')
ws.setFormula('E2', '=GETPIVOTDATA("Sum of Sales",A1,"Region","West")')
console.log(ws.getValue('E1'), ws.getValue('E2')) // 15 50
} finally {
wb.dispose()
}from formulon import (
PivotAggregation,
PivotAxis,
PivotDataFieldInput,
PivotInput,
PivotSortOrder,
Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
cache = wb.add_pivot_cache()
for name in ("Region", "Product", "Sales"):
cache.add_field(name)
for row in [["East", "Widget", 10], ["West", "Gadget", 30], ["East", "Gadget", 5], ["West", "Widget", 20]]:
record = cache.add_record()
for field, value in enumerate(row):
cache.set_record_value(record, field, value)
pivot = ws.add_pivot(PivotInput(name="SalesByRegion", cache_id=cache.cache_id, anchor="A1"))
pivot.set_field_axis("Region", PivotAxis.ROW)
pivot.set_field_axis("Sales", PivotAxis.VALUE)
pivot.add_data_field(PivotDataFieldInput(field_index="Sales", aggregation=PivotAggregation.SUM))
pivot.update_field("Region", sort_order=PivotSortOrder.DESCENDING)
pivot.rename("Sales by region")
print(ws["A2:B3"]) # [['West', 50.0], ['East', 15.0]]
print(",".join(p.name for p in ws.list_pivots())) # Sales by region
ws.set_formula("E1", '=GETPIVOTDATA("Sales",A1,"Region","East")')
ws.set_formula("E2", '=GETPIVOTDATA("Sum of Sales",A1,"Region","West")')
print(ws["E1"], ws["E2"]) # 15.0 50.0Configure PivotTable fields covers filters, subtotals, date grouping, calculated fields and the report layouts.