Pivot Table

A pivot table reduces a large data range to a compact summary. It supports summarizing, analyzing, and visualizing data, and it provides the data operations and formatting options that make the result easier to understand.

Introduction

Pivot tables are typically used for one of four purposes:

  • Summarizing a large data range to make the overall picture visible.
  • Analyzing the data to identify patterns and relationships.
  • Exploring the data to discover rules and trends.
  • Visualizing the result to make it easier to understand.

A pivot table consists of three parts:

  • Row labels group the data by row.
  • Column labels group the data by column.
  • Values summarize the numbers at each intersection.

Row labels, column labels, and values can be rearranged at any time as the analysis requires.

Data source

In Univer Sheets, a pivot table takes either a worksheet or a data range as its source.

The first row of the source becomes the column labels, and the remaining rows contain the data. Empty rows and empty columns interfere with this layout, so the source should be kept tidy.

The data type of each column is detected automatically, which determines how the pivot table can use that field. If a column contains mixed types, the entire column is treated as a string.

Pivot tables track changes in their source: when a value in the source data changes, the table updates automatically.

Filtering

Row labels and column labels can both be filtered. A separate filter field is also available; it does not participate in the row and column layout of the report, but the values selected in it still restrict the data.

Two filtering methods are available:

  • Label filtering applies to the items of the current label dimension; in a province dimension, for example, individual provinces can be filtered out.
  • Value filtering requires a value dimension and filters on the aggregated result; for example, data whose sales are below 1000 can be hidden.

Sorting

Sorting applies to row and column fields only, in either direction. Comparisons use the localCompare method. Additional comparison methods, pinyin sorting among them, are planned.

Two sorting methods are available:

  • Label sorting applies to the items of the current label dimension; in a province dimension, this sorts by province name.
  • Value sorting requires a value dimension and sorts on the aggregated result, for example by sales amount.

Aggregation

Pivot tables support the 11 aggregation methods Excel offers: sum, count, data count, average, maximum, minimum, factorial, standard deviation, variance, population standard deviation, and population variance.

Several value dimensions can be added, and both the area they occupy (value position) and their order within that area (value index) can be configured.

This layout is complex, so only the table view is supported at present. Additional views will be added based on demand.

Drill down

Drill down refers to double-clicking a cell in the value area of a pivot table to view the detail behind that cell. The detail lists the rows that produced the number, which allows a total to be traced back to the source data.

Grouping

Univer Sheets supports date, numeric, and manual grouping.

  • Date grouping: use setDateGroupType for a derived date field. To group an original date label field by calendar unit, set setDateGroupingMode to univerAPI.Enum.PivotDateGroupingMode.ExcelLike, then call setExcelDateGroup.
  • Numeric grouping: pass a label field ID and the interval settings to setNumberGroup.
  • Manual grouping: pass the original source field ID and groups of typed members to setManualGroups. Each group requires at least two members; an empty array removes all manual groups for that field.

Slicers and timelines filter tables and pivot reports interactively.

Preset mode

Pivot tables are included in the @univerjs/preset-sheets-advanced preset, which also contains other advanced features such as drawing and watermark.

Installation

UniverSheetsAdvancedPreset from @univerjs/preset-sheets-advanced depends on UniverSheetsDrawingPreset at runtime, so @univerjs/preset-sheets-drawing must be installed first.

pnpm add @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advanced

Usage

TypeScript
import { UniverSheetsAdvancedPreset } from '@univerjs/preset-sheets-advanced'import UniverPresetSheetsAdvancedEnUS from '@univerjs/preset-sheets-advanced/locales/en-US'import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'import UniverPresetSheetsCoreEnUS from '@univerjs/preset-sheets-core/locales/en-US'import { UniverSheetsDrawingPreset } from '@univerjs/preset-sheets-drawing'import UniverPresetSheetsDrawingEnUS from '@univerjs/preset-sheets-drawing/locales/en-US'import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'import '@univerjs/preset-sheets-core/lib/index.css'import '@univerjs/preset-sheets-drawing/lib/index.css'import '@univerjs/preset-sheets-advanced/lib/index.css'const { univerAPI } = createUniver({  locale: LocaleType.EN_US,  locales: {    [LocaleType.EN_US]: mergeLocales(      UniverPresetSheetsCoreEnUS,      UniverPresetSheetsDrawingEnUS,       UniverPresetSheetsAdvancedEnUS,     ),  },  presets: [    UniverSheetsCorePreset(),    UniverSheetsDrawingPreset(),     UniverSheetsAdvancedPreset(),   ],})

If you have a commercial license for Univer, see Using License in Client for the client-side setup.

Preset configuration

UniverSheetsAdvancedPreset

2
  • pivot
    object
    Settings for the selected feature.
    • maxLimitItemCount
      numberDefault: 1000
      Maximum number of items displayed in a pivot field.

Plugin mode

Installation

pnpm add @univerjs-pro/sheets-pivot @univerjs-pro/sheets-pivot-ui

Usage

TypeScript
import { UniverSheetsPivotTablePlugin } from '@univerjs-pro/sheets-pivot'import { UniverSheetsPivotTableUIPlugin } from '@univerjs-pro/sheets-pivot-ui'import SheetsPivotTableUIEnUS from '@univerjs-pro/sheets-pivot-ui/locale/en-US'import SheetsPivotTableEnUS from '@univerjs-pro/sheets-pivot/locale/en-US'import { LocaleType, mergeLocales, Univer } from '@univerjs/core'import '@univerjs-pro/sheets-pivot-ui/lib/index.css'import '@univerjs-pro/sheets-pivot/facade'const univer = new Univer({  locale: LocaleType.EN_US,  locales: {    [LocaleType.EN_US]: mergeLocales(      SheetsPivotTableEnUS,       SheetsPivotTableUIEnUS,     ),  },})

Registering plugins

The pivot table plugin can be registered in one of two ways, depending on how much calculation the main process should retain.

Main process only

This mode is suitable for lightweight tasks and simple operations: the plugin config can remain empty, and importing UniverSheetsPivotTablePlugin is sufficient.

TypeScript
univer.registerPlugin(UniverSheetsPivotTablePlugin)univer.registerPlugin(UniverSheetsPivotTableUIPlugin)

Main and worker processes

When pivot calculation is heavy, register the plugin in both the main process and the worker process. The plugin can then use a multi-threaded layout for data distribution and calculation, which moves most of the calculation off the main process and improves overall performance.

In this mode, the main process handles data distribution, synchronization, and rendering, while the worker process performs the complex calculation. The mode is selected in the registration call through the config.

TypeScript
// main process file// Setting notExecuteFormula to true indicates that the main process does not perform calculations. It is only responsible for data distribution, synchronization, and rendering.univer.registerPlugin(UniverSheetsPivotTablePlugin, { notExecuteFormula: true })univer.registerPlugin(UniverSheetsPivotTableUIPlugin)// web worker process file// Setting notExecuteFormula to false indicates that the worker process performs the calculations.univer.registerPlugin(UniverSheetsPivotTablePlugin, { notExecuteFormula: false })

If you have a commercial license for Univer, see Using License in Client for the client-side setup.

Plugin configuration

UniverSheetsPivotTablePlugin

  • maxLimitItemCount
    numberDefault: 1000
    Maximum number of items displayed in a pivot field.
  • autoDateGroup
    booleanDefault: true
    Group date fields added to rows or columns automatically.
  • dateSystem
    DateSystemDefault: DateSystem.Date1900
    Date system used to group dates.
  • notExecuteFormula
    boolean
    Selects roles for pivot calculation. Use true on the main thread and false in the worker process. Omit it for single-threaded use.

Mobile support

Set up the mobile editor first. In the plugin-mode setup on this page, replace the desktop registrations below with the mobile exports from the same packages, and do so before opening a document. Retain the model plugins, styles, locales, and Facade imports, and register only one variant, not both.

PackageDesktop registrationMobile registration
@univerjs-pro/sheets-pivot-uiUniverSheetsPivotTableUIPluginUniverSheetsPivotTableMobileUIPlugin

Facade API

The complete Facade API type definitions are in FacadeAPI.

Importing

Plugin mode note

Only plugin mode requires importing the Facade package manually. Preset mode already includes the matching package, so no additional import is needed.

TypeScript
import '@univerjs-pro/sheets-pivot/facade'

Add a pivot table

FWorkbook.addPivotTable adds a pivot table and returns an FPivotTable instance when it succeeds.

TypeScript
// should ensure the sheet range A1:G9 is not emptyconst fWorkbook = univerAPI.getActiveWorkbook()const unitId = fWorkbook.getId()const fSheet = fWorkbook.getActiveSheet()const subUnitId = fSheet.getSheetId()const sheetName = fSheet.getSheetName()const sourceInfo = {  unitId,  subUnitId,  sheetName,  range: {    startRow: 0,    startColumn: 0,    endRow: 8,    endColumn: 6,  },}const anchorCellInfo = {  unitId,  subUnitId,  row: 20,  col: 8,}const fPivotTable = await fWorkbook.addPivotTable(sourceInfo, univerAPI.Enum.PositionTypeEnum.Existing, anchorCellInfo)const pivotTableId = fPivotTable.getPivotTableId()// add flag to avoid add pivot fields multiple timeslet hasAdded = false// the addPivotTable is async, you can add pivot fields after the pivot table is addeduniverAPI.addEvent(univerAPI.Event.PivotTableRendered, async (params) => {  if (!hasAdded && params.pivotTableId === pivotTableId) {    hasAdded = true    await fPivotTable.addField(1, univerAPI.Enum.PivotTableFiledAreaEnum.Row, 0)    await fPivotTable.addField(1, univerAPI.Enum.PivotTableFiledAreaEnum.Value, 0)  }})

Get a pivot table

FWorkbook.getPivotTableByCell finds a pivot table by its anchor cell and returns an FPivotTable if the target cell lies inside a pivot table.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const unitId = fWorkbook.getId()const fSheet = fWorkbook.getActiveSheet()const subUnitId = fSheet.getSheetId()// get pivot table by the cell in FWorkbook.const fPivotTable = fWorkbook.getPivotTableByCell(unitId, subUnitId, 0, 8)// get pivot table by the cell in FWorksheet.const pivotTable2 = fSheet.getPivotTableByCell(0, 8)

FPivotTable provides the methods used to operate a pivot table.

MethodDescription
removeRemove the pivot table from the instance.
getConfigReturn the config: the source range info, the anchor cell info, and the field config.
addFieldAdd a field to the pivot table.
removeFieldRemove a field from the pivot table.
updateFieldPositionUpdate the field's area and position in the pivot table.
updateValuePositionControl the ∑Value position.
setSubtotalTypeSet the subtotal type of the field.
setLabelSortSet the label sort of the field.
setLabelManualFilterSet the label filter of the field.
renameFieldRename the field.
setValueFilterSet the value filter.
resetReset the pivot table fields.
setFieldsConfigSet the pivot table field config.
getValueFiltersGet every value filter on the pivot table.

Event listeners

The complete event type definitions are in Events.

univerAPI.Event.BeforePivotTableAdd fires before a pivot table is added.

TypeScript
const disposable = univerAPI.addEvent(univerAPI.Event.BeforePivotTableAdd, (params) => {  const { positionType, targetCellInfo } = params  if (positionType === univerAPI.Enum.PositionTypeEnum.Existing && targetCellInfo.sheetName === 'Sheet 1') {    // Cancel the pivot table adding operation    params.cancel = true    console.log(`The pivot table can't be added to the sheet ${targetCellInfo.sheetName}`)  }})// Remove the event listener, use `disposable.dispose()`

univerAPI.Event.PivotTableAdded fires after a pivot table is added.

TypeScript
const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableAdded, (params) => {  const { positionType, targetCellInfo } = params  if (positionType === univerAPI.Enum.PositionTypeEnum.Existing) {    console.log('A pivot table created in an existing sheet')    console.log(`      The target sheet name is ${targetCellInfo.sheetName},      the target row is ${targetCellInfo.row}, the target column is ${targetCellInfo.column}    `)  } else {    console.log('A pivot table created in a new sheet')  }})// Remove the event listener, use `disposable.dispose()`

univerAPI.Event.BeforePivotTableMove fires before a pivot table is moved.

TypeScript
const disposable = univerAPI.addEvent(univerAPI.Event.BeforePivotTableMove, (params) => {  const { pivotTableId, targetCellInfo } = params  if (pivotTableId === 'pivotTable1' && targetCellInfo.sheetName === 'Sheet 1') {    // Cancel the move pivot table operation    params.cancel = true    console.log(`The pivot table can't be moved to the sheet ${targetCellInfo.sheetName}`)  }})// Remove the event listener, use `disposable.dispose()`

univerAPI.Event.PivotTableMoved fires after a pivot table is moved.

TypeScript
const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableMoved, (params) => {  const { pivotTableId, targetCellInfo, originTargetInfo } = params  if (pivotTableId === 'pivotTable1') {    console.log(`      The pivot table moved from row: ${originTargetInfo.row} & column: ${originTargetInfo.column}      to the sheet ${targetCellInfo.sheetName} row: ${targetCellInfo.row} & column: ${targetCellInfo.column}    `)  }})// Remove the event listener, use `disposable.dispose()`

univerAPI.Event.PivotTableRendered fires after a pivot table is rendered.

TypeScript
// import { unionPivotViewRange } from '@univerjs-pro/sheets-pivot';const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableRendered, (params) => {  const { pivotTableId, rangeInfo } = params  console.log(`The pivot table ${pivotTableId} has been rendered`)  if (rangeInfo) {    console.log(unionPivotViewRange(rangeInfo))  }})// Remove the event listener, use `disposable.dispose()`

univerAPI.Event.PivotTableRemoved fires after a pivot table is removed.

TypeScript
const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableRemoved, (params) => {  const { pivotTableId } = params  console.log(`The pivot table ${pivotTableId} has been removed`)})// Remove the event listener, use `disposable.dispose()`

univerAPI.Event.PivotTableFieldAdded fires after a field is added to a pivot table.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableFieldAdded, (params) => {  const { pivotTableId, fieldId, fieldArea, fieldIndex } = params  const pivotTable = fWorkbook.getPivotTableById(pivotTableId)  const fieldSetting = pivotTable.getFieldSetting(fieldId)  console.log(fieldSetting)})// Remove the event listener, use `disposable.dispose()`

univerAPI.Event.PivotTableFieldRemoved fires after a field is removed from a pivot table.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableFieldRemoved, (params) => {  const { pivotTableId, fieldId } = params  const pivotTable = fWorkbook.getPivotTableById(pivotTableId)  const fieldSetting = pivotTable.getFieldSetting(fieldId)  console.log(fieldSetting)})// Remove the event listener, use `disposable.dispose()`

univerAPI.Event.PivotTableFieldMoved fires after a field moves within a pivot table.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableFieldMoved, (params) => {  const { pivotTableId, fieldId, fieldArea, fieldIndex } = params  const pivotTable = fWorkbook.getPivotTableById(pivotTableId)  const fieldSetting = pivotTable.getFieldSetting(fieldId)  console.log(`The source name ${fieldSetting.sourceName} the display name ${fieldSetting.displayName}`)})// Remove the event listener, use `disposable.dispose()`

univerAPI.Event.PivotTableFieldCollapseChanged fires after a dimension is expanded or collapsed in a pivot table.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableFieldCollapseChanged, (params) => {  const { pivotTableId, fieldId, isCollapsed } = params  const pivotTable = fWorkbook.getPivotTableById(pivotTableId)  const fieldSetting = pivotTable.getFieldSetting(fieldId)  console.log(`The source name ${fieldSetting.sourceName} the display name ${fieldSetting.displayName}`)})// Remove the event listener, use `disposable.dispose()`

univerAPI.Event.PivotTableFieldFilterChanged fires after a dimension is filtered in a pivot table.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableFieldFilterChanged, (params) => {  const { pivotTableId, fieldId, filter } = params  const pivotTable = fWorkbook.getPivotTableById(pivotTableId)  const fieldSetting = pivotTable.getFieldSetting(fieldId)  console.log(`The Checklist filter value is ${fieldSetting.filterInfo.checklist}`)})// Remove the event listener, use `disposable.dispose()`

univerAPI.Event.PivotTableFieldSortChanged fires after a dimension is sorted in a pivot table.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableFieldSortChanged, (params) => {  const { pivotTableId, fieldId, sort } = params  const pivotTable = fWorkbook.getPivotTableById(pivotTableId)  const fieldSetting = pivotTable.getFieldSetting(fieldId)  console.log(`The sort info is ${fieldSetting.sortInfo}`)})// Remove the event listener, use `disposable.dispose()`

univerAPI.Event.PivotTableFieldSettingChanged fires after a dimension's setting changes in a pivot table.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableFieldSettingChanged, (params) => {  const { pivotTableId, fieldId, setting } = params  const pivotTable = fWorkbook.getPivotTableById(pivotTableId)  const fieldSetting = pivotTable.getFieldSetting(fieldId)  console.log(`The source name ${fieldSetting.sourceName} the display name ${fieldSetting.displayName}`)})// Remove the event listener, use `disposable.dispose()`

univerAPI.Event.PivotTableValuePositionChanged fires after a value's position changes in a pivot table.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableValuePositionChanged, (params) => {  const { pivotTableId, valueId, position } = params  const pivotTable = fWorkbook.getPivotTableById(pivotTableId)  const valueSetting = pivotTable.getValueSetting(valueId)  console.log(`The source name ${valueSetting.sourceName} the display name ${valueSetting.displayName}`)})// Remove the event listener, use `disposable.dispose()`

Blocked output

The report needs room to expand. Existing cell content, merged cells, or another pivot table can block the output area. Clear the obstruction or move the report to an empty range.

Show values as

setShowDataAs() on a value field changes the value that field displays: its share of a row, a column, or a grand total, or its difference from a base item. Only the displayed calculation changes; the source data is not modified. getShowDataAs() reads the current setting, and resetShowDataAs() restores the normal calculation.

TypeScript
const valueId = fPivotTable.getFieldIdsByArea(  univerAPI.Enum.PivotTableFiledAreaEnum.Value,)[0]if (valueId) {  await fPivotTable.setShowDataAs(valueId, {    type: univerAPI.Enum.PivotShowAsTypeEnum.percentOfGrandTotal,  })  console.log(fPivotTable.getShowDataAs(valueId))}

The example assumes an existing fPivotTable. The argument is a value field ID, not a source column or row field ID. Difference and running-total modes also require the corresponding base field and base item settings.

Copy pivot tables with a worksheet

With the pivot plugin registered, duplicating a worksheet also copies the pivot tables on that worksheet and preserves their field configuration. Each copy receives a new pivot-table ID. A source range located on the copied worksheet is redirected to the new worksheet, while a source on another worksheet or workbook retains its original reference. The copied tables participate in the undo and redo of the worksheet copy.

TypeScript
const workbook = univerAPI.getActiveWorkbook()if (!workbook) throw new Error('No active workbook')const copiedSheet = workbook.duplicateActiveSheet()console.log(copiedSheet.getSheetName())

Multiple filters and date conditions

setOptions({ allowMultipleFilters: true }) allows a member selection, a label or date condition, and a value filter to coexist on the same field. If the option is omitted or set to false, a new filter replaces the previous one instead of adding to it; disabling the option while categories conflict clears the report filters. A field still accepts at most one value filter.

setDateFilter() accepts the fixed date operators, including dateEqual, dateOlderThan, and dateBetween. expected holds Excel serial values in the workbook's date system, and a between condition takes two of them. useWholeDay: true ignores the time of day and compares whole days; if the option is omitted or set to false, the comparison uses exact serials. The argument is the report field ID, not a source column index. The following example builds on the fPivotTable above and a source column named Date.

getDateFilter() returns a detached copy of the condition, and clearDateFilter() clears the date condition and nothing else. Both commands participate in undo and collaboration. Check the boolean value they return: an active slicer can prevent an incompatible filter from being applied.

TypeScript
if (!fPivotTable) throw new Error('PivotTable not found')await fPivotTable.setOptions({ allowMultipleFilters: true })const dateField = Object.values(fPivotTable.getConfig()?.fieldsConfig.dimension ?? {})  .find((field) => field.sourceName === 'Date')if (!dateField) throw new Error('Add the Date field to the report first')await fPivotTable.setDateFilter(dateField.id, {  operator: univerAPI.Enum.ST_PivotFilterOperatorEnum.dateEqual,  expected: 45293,  useWholeDay: true,})console.log(fPivotTable.getDateFilter(dateField.id))await fPivotTable.clearDateFilter(dateField.id)

GETPIVOTDATA

=GETPIVOTDATA("Sales",$I$1,"Region","East") reads an aggregate from a visible pivot report whose upper-left cell is I1. The value field may be specified by its displayed caption or by its source name. The anchor must be a single cell reference, and field/item pairs must be supplied in full.

The current implementation reads only the visible report, scanning up to 200 rows down and 50 columns right from the anchor. It does not query hidden source records. A field/item pair that does not match, or a result that is unavailable, returns #REF!. An incorrect argument count, or an anchor that is not a single cell, returns #VALUE!.

How is this guide?

© 2026 DreamNum Co., Ltd.