Configure PivotTable fields
Once a pivot exists, each setting is its own call on the Pivot handle. This page lists those calls, reads a definition back, groups dates and numbers, and adds calculated fields and items.
Insert a PivotTable
A1:C7 holds sales by region and product. A PivotTable summarises it by the fields you choose.
Powered by the real Formulon engine (WASM) — it runs entirely in your browser, nothing is uploaded.
What you can do
- Place fields, set the report layout and change grand totals with one call each: Configure an existing pivot.
- Read a definition back, whether it was built in the session or loaded from a file: Read a definition back.
- Sort fields and control expansion: Sort order and expansion.
- Show values in another form: Show values as.
- Group dates by an explicit day interval: Group dates by an explicit day interval.
- Group numbers into ranges: Group numbers into ranges.
- Add calculated fields and items: Calculated fields and items.
Configure an existing pivot
Each structural setting is its own call on the Pivot handle. Properties of a field or an item are changed with one patch call, updateField and updateFieldItem:
- An omitted key keeps its value.
nullclears a key that has a cleared form (customName,numberFormatandsortByFieldon a field,captionon an item).- An item
captionof''is an empty label, which Excel stores, whilenullremoves the rename. - For a field's
customNameandnumberFormat,''means the same asnull. - The whole patch is checked first and applied atomically, so a rejected key changes nothing, and an empty patch changes nothing.
Items are addressed by the index addFieldItem returned, and a field by its position in the cache. A field argument also takes the source name of the cache field ('Region', resolved as names are), and so does the fieldIndex of addDataField and a filter.
Python uses the snake_case name unless the table shows otherwise.
| Task | JavaScript (pivot) |
|---|---|
| Compact, tabular, or outline form | setReportLayout, getReportLayout (Python: set_report_layout) |
| Grand totals, name, anchor | updateGrandTotals, rename, setAnchor |
| Field placement and order | setFieldAxis, setRowFieldOrder, setColumnFieldOrder, setPageFieldOrder |
| Sort and expansion | updateField(field, { sortOrder, sortByField, showDetail }) |
| Subtotals | setFieldSubtotalFunctions, updateField(field, { subtotalTop }) |
| Field properties | updateField(field, { customName, numberFormat, defaultSubtotal, insertBlankRow, fillDownLabels, showAll, subtotalTop, sortOrder, sortByField, showDetail }) (Python: update_field(field, custom_name=…)) |
| Show or hide items | addFieldItem, updateFieldItem(field, item, { visible, showDetail, caption }), clearFieldItems |
| Value fields | addDataField, setDataField, clearDataFields |
| Label and value filters | addFilter, listFilters, removeFilter, clearFilters |
| Date grouping | setFieldDateGroup (null removes the grouping) |
| Numeric grouping | setFieldNumericGroup (null removes the grouping) |
Read a definition back
A pivot's definition can be read back whether it was built in the session or loaded from a file. Each getter is a method of the Pivot handle; Python uses snake_case.
| Read | JavaScript | Python |
|---|---|---|
| Pivots on a sheet | ws.listPivots() (handles) | ws.list_pivots() |
| Name, cache | pivot.name, pivot.cache() | pivot.name, pivot.cache() |
| The definition as a record | pivot.getProperties() (PivotProperties: name, cacheId, reportLayout, grandTotals, styleOptions) | pivot.get_properties() |
| Grand totals | getGrandTotals (rows, columns) | get_grand_totals |
| Table style | getStyleOptions | get_style_options |
| Axis order | getRowFieldOrder, getColumnFieldOrder, getPageFieldOrder | get_row_field_order, get_column_field_order, get_page_field_order |
| Fields and items | listFields, getField, listFieldItems, getFieldItem | list_fields, get_field, list_field_items, get_field_item |
| Data fields | listDataFields, getDataField | list_data_fields, get_data_field |
| Filters | listFilters, getFilter | list_filters, get_filter |
| Grouping | getFieldDateGroup, getFieldNumericGroup | get_field_date_group, get_field_numeric_group |
| Cache fields and their type flags | cache.listFields() | cache.list_fields() |
| A cache cell | cache.getRecordValue(recordIndex, fieldIndex) | cache.get_record_value |
Page fields
getPageFieldOrder() and setPageFieldOrder(indices) (Python get_page_field_order, set_page_field_order) read and write the page-axis fields the way the row and column orders do. The Values level is InvalidArgument there, and a saved file lists the page fields in this order.
A page field with one item visible and the others hidden (updateFieldItem(field, item, { visible: false })) shows (Multiple Items) above the report, as Excel does, unless the file marks the field as allowing multiple selection; then it shows the item's name.
Field and data-field listings
pivot.listFields() reports each field's axis (null when it sits on none), sort, number format and subtotals, and groupBaseIndex (group_base_index).
| Member | Meaning |
|---|---|
groupBaseIndex | For a group field, the index of the field it groups, otherwise null. |
defaultSubtotal / default_subtotal | Whether the automatic subtotal shows. false whenever custom functions are set. |
subtotalFunctions / subtotal_functions | Those functions, in ascending PivotAggregation order. |
getFieldDateGroup(field) and getFieldNumericGroup(field) read the grouping itself, null for a field that is not grouped that way.
pivot.listDataFields() returns the same members as PivotDataFieldInput, with showAsBaseField / showAsBaseItem null when unset.
Style options
pivot.updateStyleOptions(patch) / update_style_options() set the table style name and the row-header, column-header, row-stripe, column-stripe and last-column toggles.
styleName:nullwrites the style element without a name.- An omitted key keeps its value, and
nullfor a toggle throwsTypeError.
A new pivot takes the pivotStyleName of the workbook's table-style defaults (PivotStyleLight16 unless set) with row headers, column headers and the last column on. getStyleOptions() returns null (None) when the definition has no style element.
Data field names
A data field added or replaced with no name is named from the profile's pivot wording, such as Sum of Sales under an English profile and 合計 / Sales under ja_JP. A name of '' is kept as an empty caption, as Excel stores it.
A name that repeats another data field's name, or a field's source or custom name, fails with StatusCode.AlreadyExists and changes nothing. An empty or blank caption counts as a name, so a second data field captioned '' or ' ' is refused as Excel refuses it, while a data field may keep the caption it already has.
Sort order and expansion
pivot.updateField(fieldIndex, { sortOrder, sortByField }) (Python update_field(field_index, sort_order=..., sort_by_field=...); C fm_sheet_update_pivot_field) takes a PivotSortOrder. Any other value is rejected.
PivotSortOrder | Value | Python | C |
|---|---|---|---|
Manual | 0 (Excel's default) | PivotSortOrder.MANUAL | FM_PIVOT_SORT_ORDER_MANUAL |
Ascending | 1 | PivotSortOrder.ASCENDING | FM_PIVOT_SORT_ORDER_ASCENDING |
Descending | 2 | PivotSortOrder.DESCENDING | FM_PIVOT_SORT_ORDER_DESCENDING |
Manual keeps the field's items in the order they were added with addFieldItem() and takes no sortByField. A field placed on an axis already lists its items, so for a custom order call clearFieldItems(field) and add them again in the order wanted; Ascending or Descending still sorts them. A Manual order with a sortByField is StatusCode.InvalidArgument, and the order is saved as sortType="manual".
For the other orders, a sortByField decides what the items are sorted by:
sortByField | Sorts by |
|---|---|
null or empty | The label. |
| A value field of the PivotTable | That field's totals. |
| A name that is no value field of the PivotTable | Fails with StatusCode.NotFound. |
The order is read from .xlsx and .xlsb, kept on refresh, and saved to both formats as Excel saves it. An ascending or descending sort, by label or by a value field, is written to .xlsb under the Windows and Mac profiles alike.
showDetail expands or collapses every item of the field; a read reports it as true only when every item and the default marker are expanded. An item collapsed through updateField or updateFieldItem keeps its own row with its totals and drops the rows of the inner fields beneath it, so the report takes fewer rows. This holds for a PivotTable loaded from a file and for one built or refreshed through the API, and the collapse is saved to .xlsx and .xlsb.
An item added by label binds to the cache's shared item of that label, so its saved <item x> matches the cache.
Axes and field order
setFieldAxis() keeps the row and column field orders in step with the field's axis, so a field moved onto the row or column axis appears without a separate order call. null takes it off every axis along with its data fields and filters.
A pivot's fields are positional over its cache's fields, so a field's index is the cache field's position.
setRowFieldOrder() / setColumnFieldOrder() set the axis's whole membership: fields left out of the list leave the axis, and a duplicate index is rejected.
clearFields() takes every field off its axis and empties the orders; the fields themselves stay.
Subtotal position
subtotalTop defaults to true in the Python, Node, and WASM bindings, as in Excel: a group's subtotal sits on its own heading row.
With false, compact and outline layouts head the group with a label-only row and close it with an "<item> Total" row in the locale's wording.
A field with custom subtotal functions labels each subtotal row with the function name in the UI locale's wording (for example East Max) in Excel's fixed function order. Two or more functions place the subtotals below the group whatever subtotalTop says.
Show values as
PivotDataFieldInput.showAs / show_as also supports PercentOf, PercentOfRunningTotal, RankAscending, and RankDescending.
Set showAsBaseField / show_as_base_field and showAsBaseItem / show_as_base_item for modes that need a base item. showAsBaseItem is an item index or PivotShowAsBase.Previous / PivotShowAsBase.Next (Python PivotShowAsBase.PREVIOUS / NEXT), and both fields read null (Python None) when no base is set. The same holds for a data field loaded from a file.
Percent of Grand Total and Index divide by the whole-table aggregate when the grand totals are hidden. Loaded x14 pivotShowAs values and subtotalHiddenItems are preserved on save.
The example below needs an engine release that reads a loaded base this way, 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 })
using loaded = formulon.Workbook.load(wb.save())
const field = loaded.sheet(0).pivot(0).listDataFields()[0]
console.log(field.showAsBaseField, field.showAsBaseItem) // null nullfrom 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))
data = wb.save()
with Workbook.load(data) as loaded:
field = loaded[0].pivot(0).list_data_fields()[0]
print(field.show_as_base_field, field.show_as_base_item) # None NoneFilter authoring and round-tripping
A filter added with pivot.addFilter() affects pivot.getLayout() and GETPIVOTDATA, is written by save(), and is listed by pivot.listFilters() after a reload.
A filter states its operand as value, a number for a value filter and a string for a label filter (a mismatch is rejected with StatusCode.InvalidArgument). The range types (ValueBetween, LabelBetween, DateBetween and their Not forms) take the upper bound in valueHigh, and no other type may set it. listFilters() returns null for an operand the filter does not have.
Loaded <filters> blocks are preserved on save, including valueEqual, valueNotEqual, valueGreaterThan, valueGreaterThanOrEqual, valueLessThan, valueLessThanOrEqual, valueBetween, and valueNotBetween.
Group dates by an explicit day interval
pivot.setFieldDateGroup(fieldIndex, { periods, calendar, intervalDays, start, end }) (Python set_field_date_group(field_index, PivotDateGroupInput(...))) groups a date field the way Excel's Group command does.
periods is a mask of PivotDatePeriod bits (Seconds, Minutes, Hours, Days, Months, Quarters, Years), and each period becomes a group field appended to the pivot cache, finest first. PivotDatePeriod.Days with intervalDays above 1 is Excel's interval-based grouping. There is no separate week granularity, so use intervalDays: 7 / interval_days=7 for a seven-day bucket.
The snippet below builds a pivot whose cache has an OrderDate field; dateField is the field's cache position or source name.
| Key | Meaning |
|---|---|
calendar | Defaults to PivotCalendar.Gregorian. |
intervalDays | Defaults to 1. |
start, end | Left out, the engine uses the field's data minimum as Start and the data maximum plus one day as End. An explicit one is a CivilTime or a Date (Python date or datetime), read through its local fields. |
autoStart, autoEnd | true makes a bound follow the field's data whatever start or end holds, and false requires the bound. |
Labels use the bucket's date range. Values below or above an explicit window are labelled <start or >end.
| Condition | Result |
|---|---|
| A zero interval | StatusCode.InvalidArgument |
An interval above 1 combined with any period but Days | StatusCode.InvalidArgument |
| A Start after End | StatusCode.InvalidArgument |
| An empty or unknown mask | StatusCode.InvalidArgument |
A field holding anything but dates (values from date-formatted cells or given as Date, Python date or datetime) | StatusCode.PreconditionFailed, even for plain numbers that are valid serials; group them with setFieldNumericGroup instead |
pivot.setFieldDateGroup(fieldIndex, null) (Python set_field_date_group(field_index, None)) removes the grouping, and does nothing for a field that is not grouped.
pivot.getFieldDateGroup(field) (Python get_field_date_group) reads the grouping back as a PivotDateGroup: the members of the input with the stored bounds as CivilTime records (Python naive datetime), plus autoStart and autoEnd, which are true while a bound follows the field's data. A bound holds its stored value even then. setFieldDateGroup takes the record back as it is.
The date field is addressed by its cache position or source name:
import createFormulon, { PivotAggregation, PivotAxis, PivotCalendar, PivotDatePeriod } from '@libraz/formulon'
const formulon = await createFormulon()
using wb = formulon.Workbook.createDefault()
const ws = wb.sheet(0)
ws.setValues('A1', [
['OrderDate', 'Sales'],
[new Date(2026, 0, 5), 10], [new Date(2026, 0, 9), 20], [new Date(2026, 0, 14), 30],
])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'Sheet1!A1:B4' })
cache.refresh()
const pivot = ws.addPivot({ name: 'ByWeek', cacheId: cache.cacheId, anchor: 'D1' })
pivot.setFieldAxis('OrderDate', PivotAxis.Row)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
const dateField = 'OrderDate'
pivot.setFieldDateGroup(dateField, {
periods: PivotDatePeriod.Days,
calendar: PivotCalendar.Gregorian,
intervalDays: 7,
})
const group = pivot.getFieldDateGroup(dateField)
console.log(group.intervalDays, group.autoStart, group.autoEnd) // 7 true true
console.log(JSON.stringify(ws.getValues('D1:E4')))
// [["Row Labels","Sum of Sales"],["1/5/26 - 1/11/26",30],["1/12/26 - 1/15/26",30],["Grand Total",60]]from datetime import date
from formulon import (
PivotAggregation, PivotAxis, PivotCalendar, PivotDataFieldInput, PivotDateGroupInput, PivotDatePeriod,
PivotInput, PivotWorksheetSourceInput, Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values('A1', [
['OrderDate', 'Sales'],
[date(2026, 1, 5), 10], [date(2026, 1, 9), 20], [date(2026, 1, 14), 30],
])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range='Sheet1!A1:B4'))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name='ByWeek', cache_id=cache.cache_id, anchor='D1'))
pivot.set_field_axis('OrderDate', PivotAxis.ROW)
pivot.add_data_field(PivotDataFieldInput(field_index='Sales', aggregation=PivotAggregation.SUM))
date_field = 'OrderDate'
pivot.set_field_date_group(
date_field,
PivotDateGroupInput(periods=PivotDatePeriod.DAYS, calendar=PivotCalendar.GREGORIAN, interval_days=7),
)
group = pivot.get_field_date_group(date_field)
print(group.interval_days, group.auto_start, group.auto_end) # 7 True True
print(ws.get_values('D1:E4'))
# [['Row Labels', 'Sum of Sales'], ['1/5/26 - 1/11/26', 30.0], ['1/12/26 - 1/15/26', 30.0], ['Grand Total', 60.0]]Group numbers into ranges
pivot.setFieldNumericGroup(field, { interval, start, end }) (Python set_field_numeric_group(field, PivotNumericGroupInput(...))) groups a number field into ranges of interval, as Excel's Group command does for numbers.
The items are, in order:
<startfor values belowstart.- One range per
intervalfromstartwhile the range starts at most atend(0-99,100-199for an interval of 100 from 0). >the first bound past the last range.
Those integer-form labels need whole settings and whole source values. When any source value is fractional, the ranges read 0-100, 100-200 and so on, as Excel labels them.
The interval and the bounds may be fractional, and the labels use the workbook locale's decimal separator: an interval of 0.5 from 0 gives 0-0.5, 0.5-1 and so on, and 0-0,5, 0,5-1 under de_DE.
An omitted start or end follows the field's smallest or largest value, and autoStart / autoEnd work as for a date group.
| Condition | Result |
|---|---|
| A non-positive or non-finite interval or bound | StatusCode.InvalidArgument |
| A start after the end | StatusCode.InvalidArgument |
| A field holding anything but numbers | StatusCode.PreconditionFailed |
getFieldNumericGroup(field) (Python get_field_numeric_group) reads the grouping back as a PivotNumericGroup with autoStart / autoEnd, which setFieldNumericGroup takes back as it is, and setFieldNumericGroup(field, null) removes it.
A numeric grouping in a loaded file, which Excel stores on the grouped field itself, is evaluated, filtered and refreshed the same way, and is written back to .xlsx and .xlsb.
A grouping is written into the report cells when it is set:
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', 40], ['West', 85], ['East', 120], ['West', 160]])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'Sheet1!A1:B5' })
cache.refresh()
const pivot = ws.addPivot({ name: 'BySize', cacheId: cache.cacheId, anchor: 'D1' })
pivot.setFieldAxis('Sales', PivotAxis.Row)
pivot.addDataField({ fieldIndex: 'Region', aggregation: PivotAggregation.Count })
pivot.setFieldNumericGroup('Sales', { interval: 100, start: 0, end: 199 })
console.log(pivot.getFieldNumericGroup('Sales')) // { interval: 100, start: 0, end: 199, autoStart: false, autoEnd: false }
// The report cells hold the groups.
console.log(JSON.stringify(ws.getValues('D1:E4')))
// [["Row Labels","Count of Region"],["0-99",2],["100-199",2],["Grand Total",4]]from formulon import (
PivotAggregation, PivotAxis, PivotDataFieldInput, PivotInput, PivotNumericGroupInput,
PivotWorksheetSourceInput, Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values('A1', [['Region', 'Sales'], ['East', 40], ['West', 85], ['East', 120], ['West', 160]])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range='Sheet1!A1:B5'))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name='BySize', cache_id=cache.cache_id, anchor='D1'))
pivot.set_field_axis('Sales', PivotAxis.ROW)
pivot.add_data_field(PivotDataFieldInput(field_index='Region', aggregation=PivotAggregation.COUNT))
pivot.set_field_numeric_group('Sales', PivotNumericGroupInput(interval=100, start=0, end=199))
print(pivot.get_field_numeric_group('Sales'))
# The report cells hold the groups.
print(ws.get_values('D1:E4'))
# PivotNumericGroup(interval=100.0, start=0.0, end=199.0, auto_start=False, auto_end=False)
# [['Row Labels', 'Count of Region'], ['0-99', 2.0], ['100-199', 2.0], ['Grand Total', 4.0]]A pivot field or data-field number format is a format code such as #,##0.00 or 0.0%; pass the code itself. A built-in format is its code too. A string that is not a valid format code is rejected.
Calculated fields and items
Calculated fields
A calculated field is a cache field whose value is a formula over the other cache fields. cache.addCalculatedField(name, formula) (Python add_calculated_field) appends it as the last cache field and returns its index. The formula is in English canonical form, names cache fields only, and quotes a name with spaces as 'Net Amt'.
The new field is placed on a pivot like any other, by its name. cache.setCalculatedFieldFormula(fieldIndex, formula) replaces the formula, and cache.removeCalculatedField(fieldIndex) removes the field together with its data fields in every pivot.
Calculated items
A calculated item is a formula over items of one field. cache.addCalculatedItem(fieldIndex, name, formula) adds it to cache field fieldIndex and returns its position in solve order. The formula names items the field already holds as shared items, as East, 'North East', Region[East], Region[2] or Region[-1].
| Call | Does |
|---|---|
cache.listCalculatedItems() | Lists the items in solve order (fieldIndex, name, formula with its leading =, scoped). |
cache.setCalculatedItemFormula(index, formula) | Changes one item's formula. |
cache.removeCalculatedItem(index) | Removes one item. |
cache.moveCalculatedItem(index, newIndex) | Reorders them. |
Python spells these list_calculated_items, set_calculated_item_formula, remove_calculated_item and move_calculated_item.
Calculated items that name each other in a loop, as a loaded file can hold, give #REF! in the cells the loop reaches.
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 })
cache.addCalculatedField('Bonus', 'Sales*0.1')
pivot.setFieldAxis('Bonus', PivotAxis.Value)
pivot.addDataField({ name: 'Sum of Bonus', fieldIndex: 'Bonus', aggregation: PivotAggregation.Sum })
cache.addCalculatedItem(0, 'Total', 'East+West')
console.log(cache.listCalculatedItems()[0].formula) // =Region[East]+Region[West]
console.log(pivot.getLayout().cells.map((cell) => cell.value).join(' | '))
// Row Labels | Sum of Sales | Sum of Bonus | East | 10 | 1 | Total | 40 | 4 | West | 30 | 3 | Grand Total | 80 | 8from 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))
cache.add_calculated_field('Bonus', 'Sales*0.1')
pivot.set_field_axis('Bonus', PivotAxis.VALUE)
pivot.add_data_field(PivotDataFieldInput(
name='Sum of Bonus', field_index='Bonus', aggregation=PivotAggregation.SUM,
))
cache.add_calculated_item(0, 'Total', 'East+West')
print(cache.list_calculated_items()[0].formula) # =Region[East]+Region[West]
print(' | '.join(str(cell.value) for cell in pivot.get_layout().cells))
# Row Labels | Sum of Sales | Sum of Bonus | East | 10.0 | 1.0 | Total | 40.0 | 4.0 | West | 30.0 | 3.0 | Grand Total | 80.0 | 8.0Cache state and options
The cache keeps the rest of its state behind the same handle.
| Call | Does |
|---|---|
cache.getRecordCount() and cache.clearRecords() (Python get_record_count, clear_records) | Count and drop the records. |
cache.listFieldSharedItems(fieldIndex) and cache.clearFieldSharedItems(fieldIndex) | Read and drop one field's shared items. |
cache.getWorksheetSource() | Returns the source set with setWorksheetSource, or null (Python None) when the cache has none. |
cache.getOptions() / cache.updateOptions(patch) | Read and write saveData, refreshOnLoad and missingItemsLimit. |
wb.removePivotCache(cache) (Python remove_pivot_cache) | Removes a cache. Fails while a pivot still references it. |
missingItemsLimit is 0 to keep no missing items, up to 1048576; automatic is null in JavaScript and -1 in Python. An omitted member keeps its value, and Python passes them as keyword arguments (cache.update_options(refresh_on_load=True)).
Pivot options and detail
A pivot has its own options as well.
| Call | Does |
|---|---|
pivot.getOptions() / pivot.updateOptions(patch) (Python get_options / update_options) | Cover the PivotTable Options. |
pivot.updateField(fieldIndex, { showDetail }) | Expands or collapses a whole field. |
pivot.getDataFieldDefaultName(fieldIndex, aggregation) | Returns the name a new data field would get. |
pivot.showDetails('F2') (or showDetails(row, col); Python show_details) | Writes the records behind a data cell onto a new sheet inserted before the pivot's sheet and returns that sheet. |