Birch UI v0.1
Pricing

Pivot tablesSpreadsheet

Summarise a range or table in a pivot table that lives in the sheet, with row, column, value and filter fields, compact, outline and tabular layouts, label, value and date filters, calculated fields, GETPIVOTDATA, a field list panel, drill-down and automatic refresh.

Open .md

A pivot table groups and aggregates a block of data and writes the result into cells. The cells are a live region: when the source data changes, the pivot recalculates and rewrites its range.

Create a pivot table#

TypeScript
const name = sheet.insertPivotTable({
  source: 'Sales!A1:F2000',
  destination: 'H2',
  rows: [{ field: 'Region' }, { field: 'Product' }],
  columns: [{ field: 'Order Date', groupBy: 'year' }],
  values: [
    { field: 'Revenue', aggregate: 'sum', numberFormat: '#,##0' },
    { field: 'Revenue', aggregate: 'sum', showAs: 'percentOfColumn', name: 'Share' },
  ],
  filters: [{ field: 'Channel', selected: ['Online'] }],
});
PivotTableOptionsinterface@birchui/spreadsheetFull reference
PropertyTypeDescription
nameoptionalstring—
destinationoptionalstring—
columnsPivotField[]Inherited from PivotTableJSON.
rowsPivotField[]Inherited from PivotTableJSON.
styleoptionalPivotStyle | undefinedInherited from PivotTableJSON.
sourcestringInherited from PivotTableJSON.
valuesPivotValueField[]Inherited from PivotTableJSON.
filtersoptionalPivotFilterField[] | undefinedInherited from PivotTableJSON.
calculatedFieldsoptionalPivotCalculatedField[] | undefinedInherited from PivotTableJSON.
grandTotalsoptional{ rows?: boolean; columns?: boolean; } | undefinedInherited from PivotTableJSON.
layoutoptionalPivotLayout | undefinedInherited from PivotTableJSON.
repeatItemLabelsoptionalboolean | undefinedInherited from PivotTableJSON.
subtotalPositionoptional"top" | "bottom" | undefinedInherited from PivotTableJSON.
valuesOnRowsoptionalboolean | undefinedInherited from PivotTableJSON.
Property Meaning
source A range with a header row, such as 'Sales!A1:F2000', or the name of a table. A table source follows the table as it grows.
destination The top-left cell of the output. With a sheet prefix the pivot goes on that sheet. Without a destination a new sheet named Pivot1, Pivot2, … is added after the source sheet.
rows, columns Fields to group by, outermost first.
values Fields to aggregate.
filters Page filters, shown above the table. selected lists the items to keep; leave it out for all.
grandTotals { rows, columns }. Set either to false to drop the grand total column or row.
layout 'tabular' (default), 'outline' or 'compact'. See Report layout.
repeatItemLabels true writes the outer labels on every row in the tabular and outline layouts.
subtotalPosition 'top' (default) or 'bottom' in the outline and compact layouts. Tabular subtotals are always below the group.
name A unique name. The default is PivotTable1, PivotTable2, …

Field names match the header cells, ignoring case. An unknown field is skipped.

A pivot table that is defined in the workbook JSON (sheets[].pivotTables) or comes from an xlsx file is calculated and written into its range when the workbook is loaded, so the definition alone is enough. Header and grand-total cells get a light fill with dark text, which stays readable in the dark theme.

Row and column fields#

PivotFieldinterface@birchui/spreadsheetFull reference
PropertyTypeDescription
fieldstring—
groupByoptionalPivotDateGrouping—
sortoptional'ascending' | 'descending'—
subtotaloptionalboolean—
layoutoptionalPivotLayout—
hiddenItemsoptionalstring[]—
calculatedItemsoptionalPivotCalculatedItem[]—
valueFilteroptionalPivotValueFilter—
labelFilteroptionalPivotLabelFilter—
dateFilteroptionalPivotDateFilter—
  • sort: 'ascending' (default) or 'descending'. Numbers sort numerically, text ignores case, blanks come last.
  • groupBy: 'year', 'quarter' or 'month' groups a date column. Items are labelled 2025, 2025-Q1 and 2025-03 and sort chronologically.
  • subtotal: with two or more row fields, each outer field gets a subtotal row such as North Total, and with two or more column fields each outer field gets a subtotal column. Set false to leave it out.
  • labelFilter, dateFilter and valueFilter: see Filters on row and column fields.

Value fields#

PivotValueFieldinterface@birchui/spreadsheetFull reference
PropertyTypeDescription
fieldstring—
aggregateoptionalPivotAggregate—
showAsoptionalPivotShowAs—
nameoptionalstring—
numberFormatoptionalstring—
aggregate Result
sum, average, min, max Over the numeric values. Text, blanks and errors are ignored.
count Number of non-blank values.
distinctCount Number of different non-blank values.

The default is sum when the column holds numbers and count otherwise. Subtotals and grand totals are calculated from the underlying records, so an average of averages is never shown.

showAs Result
value (default) The aggregate itself.
percentOfTotal Share of the grand total.
percentOfRow Share of the row total.
percentOfColumn Share of the column total.

Percent modes are formatted as 0.00%. name replaces the caption (Sum of Revenue), and numberFormat takes any format code.

Report layout#

layout chooses how row fields are laid out, as Design › Report Layout does in Excel. With rows: [{ field: 'Region' }, { field: 'Product' }] and one value:

layout Label columns An outer item
'tabular' One per row field Shares the row of its first inner item. Its subtotal is a North Total row below the group.
'outline' One per row field Has a row of its own above its inner items, with the subtotal on that row.
'compact' One, headed Row Labels Has a row of its own; inner items are indented below it in the same column.
TypeScript
sheet.insertPivotTable({
  source: 'Sales!A1:F2000',
  destination: 'H2',
  rows: [{ field: 'Region' }, { field: 'Product' }],
  columns: [],
  values: [{ field: 'Revenue' }],
  layout: 'compact',
});
sheet.updatePivotTable('PivotTable1', { layout: 'outline', subtotalPosition: 'bottom', repeatItemLabels: true });
  • subtotalPosition: 'bottom' leaves the outer item's own row without values and adds a North Total row below the group. It has no effect in the tabular layout.
  • An outer field with subtotal: false keeps its own row in the outline and compact layouts, without values.
  • repeatItemLabels fills the label cells that are otherwise left blank. The compact layout has one label column, so it has nothing to repeat.
  • layout on a row field overrides the report layout for that field; see A layout per field.
  • A pivot without layout is tabular, as before, so existing workbooks look the same.

Column fields are laid out the same way in every layout: one header row per field, with the subtotal column of an outer item, such as Online Total, to the right of its inner items.

A layout per field#

rows[n].layout sets the form of one row field. It matters for every row field but the last. A compact field shares its column with the next field, which is indented under it; an outline field has its own column and puts each item on a row of its own; a tabular field has its own column and puts each item on the row of its first inner item, with its subtotal below. When every field has the same form, the result is the same as that report layout. In the field list, the menu of a row field has Layout of this field. A file that mixes forms is read with the form of its first row field as the report layout and the others on their fields.

Values on rows#

With two or more value fields, valuesOnRows: true (Values on rows in the field list) gives each value a row instead of a column: a Values column follows the row labels, every item has one row per value, and so do subtotals and the grand total. Column fields then have one column per item. Excel nests the values under the items in its compact form; here they always get their own column.

Hidden items#

hiddenItems on a row or column field lists the items to leave out, by their label. Show items… in the field's menu opens the list with a box per item. Hidden items are left out of subtotals and grand totals too. A list that names every item is ignored, with a warning. Date-grouped fields cannot hide items.

PivotTable styles and banding#

style paints the pivot: name is one of Excel's PivotStyleLight1 to 28, PivotStyleMedium1 to 28 or PivotStyleDark1 to 28, rowStripes and columnStripes band every second data row or value column, and columnHeaders: false or rowHeaders: false turn the header formatting of the header rows or of the subtotal labels off. The field list has a style list and two banding boxes. The name and the flags are saved to xlsx exactly. The colours are derived from the style's family, number and the Office accent colours, as for table styles, and are close to Excel's rather than identical; a custom style defined in a file is kept by name and drawn as PivotStyleLight16. Without style a pivot looks as it did before.

Refresh#

The pivot refreshes by itself after edits, pastes, fills, undo and redo that change its source. The refresh is not a separate undo step: undoing the source edit brings the old pivot back.

TypeScript
sheet.refreshPivotTable('PivotTable1');
sheet.refreshPivotTable();
sheet.on('pivotTableRefreshed', ({ sheet: sheetName, name, range }) => {
  console.log(`${name} now covers ${sheetName}!${range}`);
});

Call refreshPivotTable() after changes the widget cannot see, for example when a formula in the source depends on NOW(). Data › Refresh all and Formulas › Calculate now do the same.

When the output grows or shrinks, cells that are no longer part of the pivot are cleared. Keep the area below and to the right of a pivot free: a refresh overwrites whatever is in its way.

Change a pivot table#

TypeScript
sheet.updatePivotTable('PivotTable1', {
  rows: [{ field: 'Product', sort: 'descending' }],
  values: [{ field: 'Units', aggregate: 'average' }],
});
sheet.updatePivotTable('PivotTable1', { destination: 'K10' });
sheet.removePivotTable('PivotTable1');
sheet.getPivotTables();

updatePivotTable merges the changes into the definition and rewrites the output as one undo step. removePivotTable clears the output and removes slicers connected to it.

The field list#

Insert › PivotTable asks for the source and the location, creates an empty pivot and opens the PivotTable Fields panel beside the grid. Open it again with Data › Field list, the cell menu, or sheet.openDialog('pivotFields') while the active cell is inside a pivot.

  • Tick a field to add it: text fields go to Rows, numeric fields to Values. Untick to remove it everywhere.
  • Drag a field between Filters, Columns, Rows and Values, or within an area to reorder it.
  • Click a field, or press Enter on it, for its menu: move up or down, move to another area, summarise by, show values as, sort, group dates by, subtotals, value filter, label filter, date filter, calculated item and remove.
  • Report layout chooses compact, outline or tabular. Repeat item labels and Subtotals below the group set the two layout options; each is disabled where it has no effect.
  • Calculated field… at the bottom of the panel adds a calculated field and puts it in Values.
Keys in an area Action
↑ ↓, Home, End Move between fields
Alt + ↑, Alt + ↓ Reorder the field
Enter, Space, Shift + F10 Open the field's menu
Delete Remove the field
Escape Close the panel and return to the grid

Each move is announced to screen readers, for example "Region moved to Rows, position 2".

Drill down#

Double-click a value, a subtotal or a grand total to see the rows behind it. A new sheet named Detail1, Detail2, … is added with the header row and the matching source rows, including their number formats.

TypeScript
const detailSheet = sheet.drillDownPivot('I4');

drillDownPivot(address) returns the new sheet's name, or undefined when the address is not a value cell of a pivot.

Saving and Excel files#

The definition is stored per sheet in the workbook JSON, next to the rendered cells:

TypeScript
sheet.toJSON().sheets[0].pivotTables;
// [{ name: 'PivotTable1', source: 'Sales!A1:F2000', destination: 'H2', rows: [...], columns: [...],
//    values: [...], range: 'H2:K14' }]
PivotTableJSONinterface@birchui/spreadsheetFull reference
PropertyTypeDescription
namestring—
sourcestring—
destinationstring—
rowsPivotField[]—
columnsPivotField[]—
valuesPivotValueField[]—
filtersoptionalPivotFilterField[]—
calculatedFieldsoptionalPivotCalculatedField[]—
grandTotalsoptional{ rows?: boolean; columns?: boolean }—
layoutoptionalPivotLayout—
repeatItemLabelsoptionalboolean—
subtotalPositionoptional'top' | 'bottom'—
valuesOnRowsoptionalboolean—
styleoptionalPivotStyle—
rangeoptionalstring—

range is the area the pivot last wrote to. Loading the JSON restores a working pivot.

In an xlsx export a pivot table is written as a real PivotTable: the cache definition, the cache records, the pivot table definition and the workbook's list of caches. The layout, the subtotal position, repeated labels, column subtotals, calculated fields and label, value and date filters are part of that definition. The calculated cells are written too, with their formatting, so programs that do not read pivot tables show the numbers. Importing the file reads the definition back into pivotTables and calculates it again.

Things to know:

  • A distinct count is written as calculated cells only. Excel offers Distinct Count only for a PivotTable on the Data Model; the file format has no distinct count for a PivotTable on a worksheet range, so writing one would give a file Excel repairs. The file holds the numbers, and comes back as plain cells.
  • A pivot with a calculated item, with the same source column in two places, with a date or value filter on a date-grouped field, or with a calculated field whose formula uses a function outside the eleven is written as calculated cells only as well. Keep the workbook JSON if the pivot must stay a pivot.
  • jsonToXlsxWithReport() and exportXlsx({ onReport }) list every pivot that was written as cells only under report.adjusted, with the reason, for example Products is written as calculated cells only because a distinct count needs the Data Model, which a PivotTable on a worksheet range cannot use.
  • A dynamic date filter such as thisMonth is stored by name, together with the dates it covers on the day of the export. Pass now to jsonToXlsx() to fix that day.
  • A pivot table in a file that uses something this model lacks is kept in the file unchanged and is not read into pivotTables: an external or data model (OLAP) source, calculated items, a calculated field with a function outside the eleven, a filter by a fixed month or quarter, two label filters on one field, values placed between row fields, hidden items of a date-grouped field, or a layout that would overwrite neighbouring cells here. The component shows the cells stored in the file, and the import report gives the reason for each.
  • openpyxl reads the exported pivot tables with their layout, filters and calculated fields. LibreOffice reads them as pivot tables, keeps the layout and calculated fields, and drops label, value and date filters and repeated labels. Nothing is tested in Microsoft Excel.

Pivot tables in files has the details.

Calculated fields and items#

A calculated field is a value computed from other fields. Its formula works on the sum of each field it names, for the records behind each cell, so =Revenue/Units gives a true average price in every row and in the totals:

TypeScript
sheet.insertPivotTable({
  source: 'Orders',
  destination: 'H2',
  rows: [{ field: 'Region' }],
  columns: [],
  values: [{ field: 'Revenue' }, { field: 'Unit price', numberFormat: '0.00' }],
  calculatedFields: [{ name: 'Unit price', formula: '=Revenue/Units' }],
});

A calculated item is an extra item of a row or column field, computed from other items of that field for every value:

TypeScript
sheet.updatePivotTable('PivotTable1', {
  rows: [{ field: 'Region', calculatedItems: [{ name: 'Coasts', formula: '=East+West' }] }],
});
  • Formulas take numbers, the names of fields or items, + - * / ^ %, comparisons, parentheses and the functions IF, IFERROR, ABS, ROUND, INT, SQRT, MIN, MAX, AND, OR and NOT. Put a name in single quotes when it has spaces or punctuation: ='Unit Cost'*Units. Cell references and other functions are not available.
  • A formula that fails shows its error in the cell, such as #DIV/0!. A formula that cannot be read, or an item whose name is already an item of the field, is left out and reported in the console.
  • A calculated item is listed after the items of the field and is counted in subtotals and grand totals of sums and counts, as in Excel; averages, minimums, maximums and distinct counts in totals ignore it. An item missing under one parent counts as zero.
  • A calculated item has no source rows, so drilling into it gives nothing, and it cannot be used on a field that is grouped by date.
  • A source column takes precedence over a calculated field with the same name.
  • In an xlsx file a calculated field is a cache field with its formula, and the value is a data field on it, as Excel writes them. The formula is stored without the =, with names that are not plain identifiers in single quotes. Calculated items are not written as part of a PivotTable.

Filters on row and column fields#

A row or column field can carry a label filter or a date filter, and a value filter on top of either. Filtered items are left out of the pivot, and subtotals and grand totals cover only what is shown.

Label filters#

TypeScript
sheet.updatePivotTable('PivotTable1', {
  rows: [{ field: 'Product', labelFilter: { operator: 'beginsWith', operand: 'Espresso' } }],
});
PivotLabelFilterinterface@birchui/spreadsheetFull reference
PropertyTypeDescription
operatorPivotLabelFilterOperator—
operandstring—
operand2optionalstring—
operator Keeps items whose label
'equals', 'doesNotEqual' Is, or is not, operand.
'beginsWith', 'doesNotBeginWith', 'endsWith', 'doesNotEndWith', 'contains', 'doesNotContain' Starts with, ends with or contains operand.
'greaterThan', 'greaterThanOrEqual', 'lessThan', 'lessThanOrEqual' Sorts after or before operand.
'between', 'notBetween' Lies between operand and operand2, inclusive, or outside them.

Text is compared without regard to case. When the label and the operand are both numbers they are compared as numbers. * and ? are ordinary characters, not wildcards. On a date-grouped field the filter tests the group label, such as 2025 or 2025-Q1.

Date filters#

A date filter tests the date values of the field's column, whether or not the field is grouped:

TypeScript
sheet.updatePivotTable('PivotTable1', {
  rows: [{ field: 'Order Date', groupBy: 'month', dateFilter: { operator: 'thisQuarter' } }],
});
sheet.updatePivotTable('PivotTable1', {
  rows: [{ field: 'Order Date', dateFilter: { operator: 'between', date: '2025-01-01', date2: '2025-06-30' } }],
});
PivotDateFilterinterface@birchui/spreadsheetFull reference
PropertyTypeDescription
operatorPivotDateFilterOperator—
dateoptionalstring—
date2optionalstring—
operator Keeps
'equals', 'doesNotEqual' Records on date, or on any other day.
'before', 'beforeOrEqual', 'after', 'afterOrEqual' Records before or after date.
'between', 'notBetween' Records from date to date2, inclusive, or outside that range.
'today', 'yesterday', 'tomorrow' One day.
'thisWeek', 'lastWeek', 'nextWeek' A week from Sunday to Saturday.
'thisMonth', 'lastMonth', 'nextMonth', 'thisQuarter', 'lastQuarter', 'nextQuarter', 'thisYear', 'lastYear', 'nextYear' A calendar month, quarter or year.
'yearToDate' 1 January of this year up to and including today.
  • date and date2 are ISO dates, 'YYYY-MM-DD'. A date that cannot be read is ignored, and the pivot is not filtered by it.
  • The time of day is ignored. Cells that hold text, or nothing, do not pass a date filter.
  • "Today" comes from the now option of the component or the engine, the same clock TODAY() uses. A pivot with a period filter is calculated again on a refresh after the day changes; it does not refresh by itself at midnight.
  • A field has either a label filter or a date filter. Setting one from the field list removes the other.

Value filters#

A value filter keeps the items of a row or column field whose value passes a test, and totals only what is shown:

TypeScript
sheet.updatePivotTable('PivotTable1', {
  rows: [{ field: 'Product', valueFilter: { operator: 'top', operand: 5 } }],
});
operator Keeps
'top', 'bottom' The operand items with the largest or smallest values. Items that tie with the last one kept are kept too. With by: 'percent' the largest (or smallest) items are kept until together they reach operand percent of the total; with by: 'sum' until their sum reaches operand. The item that crosses the mark is kept. The dialog has Counted by for this.
'greaterThan', 'greaterThanOrEqual', 'lessThan', 'lessThanOrEqual', 'equal', 'notEqual' Items whose value compares with operand.
'between' Items whose value lies between operand and operand2, inclusive.

value is the position of the value field to test in values, 0 by default. The filter looks at the field's own total: for an inner field it is applied inside each outer item. Items with no value, and calculated items, are not filtered. Label and date filters are applied first, so "top 5" means the top five of what they leave.

In the field list, open the field's menu and choose Label filter…, Date filter… or Value filter…. A filter that is set has a tick in the menu, and Clear label filter, Clear date filter or Clear value filter removes it.

GETPIVOTDATA#

GETPIVOTDATA(data_field, pivot_table, [field1, item1], …) returns a value the pivot shows:

text
=GETPIVOTDATA("Revenue", $H$2)
=GETPIVOTDATA("Revenue", $H$2, "Region", "North")
=GETPIVOTDATA("Sum of Revenue", $H$2, "Region", "North", "Order Date", 2025)
  • data_field is the caption of a value field (Sum of Revenue) or the name of its source field. pivot_table is any cell of the pivot.
  • With no pairs the result is the grand total. With pairs it is the value, subtotal or total for those items. Names ignore case. An item of a date-grouped field is its label: 2025, "2025-Q1" or "2025-03".
  • The result is #REF! when the pivot does not show that combination: an item that is not there or is filtered out, a subtotal or grand total that is switched off, an inner field without its outer fields, an empty value cell, or a reference that is not inside a pivot.
  • A pair may name a page filter field; it matches when that filter has exactly that one item selected.
  • The function is volatile. It follows edits to the source, changes to the pivot definition and slicers.
  • In the headless engine it is calculated from the current source data, so it is up to date even before refreshPivotTables() rewrites the pivot's cells.
  • The formula is stored in xlsx as typed. Excel and LibreOffice calculate it against their own pivot table.

GROUPBY and PIVOTBY build a summary with a formula instead of a pivot table. See Grouping with formulas.

Good to know#

  • The header row of the source must not be empty; a blank header is named Column N.
  • Renaming the source sheet does not update source. Use a table as the source, or call updatePivotTable(name, { source }).
  • Typing into a pivot cell is not blocked; the next refresh restores the calculated value.
  • A pivot with two or more column fields now has a subtotal column for each outer column item. Set subtotal: false on the outer column field to get the earlier layout.
  • Only the layout is modelled from Design: banded rows, blank lines after items and PivotTable styles are not.
  • The engine groups 100,000 rows in well under a second. Refreshing reads the whole source, so very large sources make every edit to them slower.

↑ ↓ to move, Enter to open, Esc to close