Pivot Tables
A pivot table summarizes worksheet records into row groups, column groups and aggregate values. Its result occupies a worksheet range. Change its source or field settings to recalculate the report; edit the source data rather than individual result cells.
Pivot tables are available through the browser editor, its Angular integration, the Node.js server package and the .NET server package. They require no additional helper package.
Create a Sales Report
In a browser application, obtain workbook from editor.workbook. The following example writes four orders and creates a formatted cross-tab on a separate worksheet. Rows identify regions, columns identify categories and the cells show revenue totals.
const workbook = editor.workbook;
const source = workbook.sheets.at(0);
source.range('A1:D5').setValues([
['Region', 'Category', 'Revenue', 'Cost'],
['Europe', 'Software', 1250, 500],
['Europe', 'Services', 700, 350],
['Americas', 'Software', 1800, 900],
['Americas', 'Services', 950, 400]
]);
const report = workbook.sheets.add('Sales Summary');
const pivot = report.pivotTables.add({
name: 'RegionalSales',
source: { sheetId: source.id, range: 'A1:D5' },
destination: { sheetId: report.id, cell: 'B3' },
rows: [{ field: 'Region' }],
columns: [{ field: 'Category' }],
values: [{ field: 'Revenue', caption: 'Sales', numberFormatCode: '$#,##0.00' }],
layout: 'tabular', style: { rowBanding: true }
});
editor.ui.pivotTables.show(pivot);
The European revenue total is 1,950 and the grand total is 4,700. The source can instead identify an Excel-style table with tableId or a defined name with namedRange. Specify exactly one source selector and its worksheet ID. Refresh resolves the current table extent or named rectangle, so a growing table does not need a fixed source address.
Insert and Configure in the Editor
Select source data with a header row, open Insert and choose PivotTable in the Tables group. In the create dialog, choose the source worksheet and range, name the report and choose a new worksheet or an existing destination cell. The result must not overlap source data, another pivot, a table, merged cells or unrelated values.
The create dialog keeps the report name above Source Data and Destination sections. Open a section to configure it; the previous one closes. The shared fixed frame keeps Cancel and Create available while the settings scroll. Create inserts the report; Cancel leaves the workbook unchanged.

Select any result cell to show the contextual PivotTable ribbon. Field List opens a resizable task pane. Check a field to add it to the report: numeric fields go to Values, and other fields go to Rows. Uncheck it to remove its assignments. Drag fields into Filters, Columns, Rows or Values to choose their placement. Assigned fields appear as bordered cards with drag handles. Arrow buttons reorder assigned fields; the settings button configures each field. Search narrows the available field list. Close the pane without removing the report. The field list uses the same sidebar style and resizing controls as Comments. Opening one feature sidebar closes the other, so the worksheet keeps usable space. Use the separator arrows, Home and End to resize it with the keyboard, or Escape while focus is inside the sidebar to close it.

The ribbon also changes source and destination, refreshes one or all reports, switches compact, outline or tabular layout, controls subtotals and grand totals, creates a chart, extracts details and removes the report. Normal undo and redo apply to these edits. The task pane supports keyboard controls in addition to dragging; its separator supports arrow-key resizing.
editor.ui.pivotTables.show(pivot); // Activate its worksheet and open fields.
editor.ui.pivotTables.hide();
editor.ui.pivotTables.insert(); // Open the create dialog.

Values and Display Calculations
Values support sum, count, countNumbers, average, min, max, product, stddev, stddevp, variance, variancep and distinctCount. Count excludes blanks; countNumbers counts finite numeric observations. Sample variance and standard deviation require at least two numeric observations. Totals reaggregate the underlying records, which keeps averages weighted correctly.
Use several values with different captions to show the same field more than once. A value's numberFormatCode formats the materialized cells. Display calculations run after aggregation and include percentages of row, column, parent and grand totals, difference, percent difference, running totals, rank and index.
pivot.update({ values: [
{ field: 'Revenue', caption: 'Sales', numberFormatCode: '$#,##0.00' },
{ field: 'Revenue', caption: 'Share', showAs: 'percentGrandTotal', numberFormatCode: '0.0%' },
{ field: 'Revenue', caption: 'Average Order', aggregation: 'average', numberFormatCode: '$#,##0.00' }
] });
Difference, percent difference, running total and ranking require an axis baseField. Set a typed baseItem for a specific comparison member; omit it for the previous displayed member in difference calculations. Division by zero and insufficient observations produce an empty result; emptyText can replace empty results with text.
Sort, Group and Collapse
An axis field sorts ascending, descending or in source order. sortByValue selects a value caption or source value field for aggregate-based sorting. Group dates into years, quarters, months or days, numeric values into intervals or scalar members into named manual groups. Date grouping uses the workbook date system for numeric dates. Use year and month fields together to separate months from different years.
pivot.setFields('columns', []);
pivot.setFields('rows', [
{ field: 'Region', sort: 'descending', sortByValue: 'Sales' },
{ field: 'Category' }
]);
pivot.setExpanded('rows', ['Europe'], false);
// Expand again without changing the source records.
pivot.setExpanded('rows', ['Europe'], true);
// A Date field must exist in the source for this example.
pivot.setFields('rows', [
{ field: 'Date', caption: 'Year', grouping: { type: 'years' } },
{ field: 'Date', caption: 'Month', grouping: { type: 'months' } }
]);
Member paths contain typed grouped values, such as [2026, '2026-01'] if those are the members returned for the grouping. Use getItems(field) to inspect available members rather than deriving them from displayed indentation. If the same field occurs with more than one grouping, getItems uses its first axis occurrence; getResult().rowPaths and columnPaths retain the complete grouped paths.
Filter and Extract Records
Header field buttons and field settings support selected or excluded members, label comparisons, aggregate-value comparisons and Top/Bottom-N filters. Filters combine with AND and do not alter the source worksheet's AutoFilter. Replace them with an empty array to clear them.
function columnName(index: number): string {
let name = '';
for (index++; index > 0; index = Math.floor((index - 1) / 26)) name = String.fromCharCode(65 + (index - 1) % 26) + name;
return name;
}
pivot.setFilters([{ field: 'Region', type: 'top', measure: 'Sales', count: 1 }]);
pivot.setFilters([{ field: 'Region', type: 'include', items: ['Europe'] }]);
const records = pivot.drillThrough(['Europe'], ['Software']);
const details = workbook.sheets.add('Order Details');
if (records.length) {
const headers = Object.keys(records[0]);
details.range(`A1:${columnName(headers.length - 1)}${records.length + 1}`).setValues([headers, ...records.map(row => headers.map(field => row[field]))]);
}
Select a value cell and use Show Details to create a worksheet of its contributing records. The API defaults to at most 1,000 records per call; pass an explicit limit up to 100,000. Partial paths select parent groups and empty paths select all filtered records.
Layout, Formatting and Display Options
Choose Options on the contextual PivotTable tab. Report layout, subtotals and grand totals are configured in this dialog; the ribbon does not duplicate these settings. It uses the editor's shared dialog with collapsible Layout, Format, Totals & Filters, Display and Data sections. Changes stay in the draft until Apply; Cancel leaves the report unchanged. Only one section is open at a time. The dialog shares its header, accordion elements, responsive layout and preview panel with Dashboard Settings. Settings use aligned rows with short captions and switches. On desktop, the settings column scrolls as one area, including the open section and its category headers; the dialog header, preview and actions stay in place. Replacement-text fields stay visible and disabled until Custom text is selected; switching back retains the draft text without moving the other settings.
The Live Preview uses the worksheet data captured when the dialog opens and the draft report settings. It shows layout, totals, merged labels and number formats without writing worksheet cells or adding undo steps. The displayed excerpt is limited to fourteen rows and eight columns; scroll horizontally to see wider columns. Interaction settings take effect after Apply. On narrow screens the preview moves below the settings.


| Section | Settings and behavior |
|---|---|
| Layout | Compact/outline/tabular form, merged and centered group labels, row-label indentation and repeated labels. Indentation remains visible but is available only in Compact layout. |
| Format | Choose original errors or custom error text, and blank or custom text for empty cells. Replacement fields retain their draft values when disabled. |
| Totals & Filters | Independent grand-total row and columns, subtotal placement, multiple filters per field, and custom-list sorting. Multiple filters use AND semantics. Turning them off rejects existing duplicate field filters rather than discarding criteria silently. |
| Display | Independent expand/collapse controls, contextual field and value-cell tooltips, field captions and filter buttons, classic grid header dragging, a separate Values caption row, and field-list sorting. Sorting the available fields does not reorder the configured report axes. |
| Data | Manual or automatic source refresh, fitting column widths and keeping existing cell formatting on refresh. Applying a new table preset resets prior cell formatting. Report filters can run down then across, or across then down; set the number of filters per column or row before wrapping. Zero keeps all filters in one column or row. |
The ribbon's Show group provides immediate toggles for Field List, +/- Buttons and Field Headers. Field List is editor UI state; the other toggles persist with the report. Field Headers updates both showHeaders and showFieldButtons; hierarchy buttons remain independently controlled by showExpandCollapseButtons. The Pivot Chart command uses the same icon as standard chart insertion.

Classic layout lets you drag a visible grid field header onto another row/column header or the Columns drop target. The field list remains available. Enabling Drag fields in the grid updates the visible Report layout choice to Tabular so each row field has a separate header. Choosing Compact or Outline turns grid dragging off; the preview and controls always show the same layout. Hiding the field headers removes the grid drag targets.
Report filters are filters on fields that are not assigned to either report axis. Their display is enabled by filterAreaLayout; existing definitions without this setting keep their original output positions. Axis-member filters remain available through their field buttons.
pivot.update({
layout: 'tabular', mergeLabels: true, compactIndent: 2,
filterAreaLayout: 'downThenOver', filterFieldsPerLine: 2,
emptyText: '—', errorText: 'Not available',
autoFitColumns: true, preserveFormatting: true,
rowGrandTotals: true, columnGrandTotals: false,
allowMultipleFiltersPerField: true,
useCustomListsForSorting: true,
customSortLists: [['Europe', 'Americas', 'Asia Pacific']],
showExpandCollapseButtons: true, showContextualTooltips: true,
classicLayout: true, showValuesRow: true, fieldListSort: 'ascending'
});
Column auto-fit uses a deterministic estimate from formatted text and font size, capped at 48–360 CSS pixels. It works without an active browser. Formatting preservation follows the existing cell positions; check the result after changing the report structure. Custom sorting supports configured text lists plus built-in English/German month and weekday names; source-order axes bypass custom sorting. A displayed error caption is presentation text: numeric getData results are null for an error group.
These settings round-trip through TXWB and the TX settings stored in XLSX. PDF exports include the materialized layout, merged labels, sizes, formatting and replacement text. UI tooltips, field-list state and drag targets are not part of PDF output. Excel-only OLAP member properties and Data Model controls are not provided for worksheet-source pivots.
Style a PivotTable
Select a result cell and open the contextual Table Design tab. Pivot results reuse the same Table Styles gallery as worksheet tables, including Light, Medium and Dark presets. Header Row, Total Row, Banded Rows, Banded Columns and Filter Button update the pivot definition in one undoable edit. Worksheet-table commands such as resizing and removing duplicates are hidden for a pivot; use Change Source and the PivotTable layout controls instead.

Use the same preset names through every API. Explicit colors override the selected preset:
pivot.update({ style: { name: 'TableStyleDark2', rowBanding: true } });
Pivot Chart opens the standard Insert Chart dialog. Choose a chart family and variant, enter a title and select the legend position. The preview uses visible detail groups without duplicating subtotals or grand totals. Cancel creates no chart; accepting creates the chart and binding in one undoable edit.
The chart follows changes to the pivot's row and column fields, measures, filters, sort order and expanded groups. Source changes appear after a manual refresh, or immediately with autoRefresh: true. An empty value area or a filter with no matching records leaves a blank chart that fills again when you restore data. Moving the report updates the chart reference; undo and redo restore the report and chart together.
Use pivot.update, setFields, setFilters and setExpanded to change chart data. Use chart.update for appearance, chart type and placement. Direct dataRange, series or orientation overrides on a bound chart are rejected so the chart stays connected to its pivot. Scatter, bubble and stock types are unsupported, matching Excel PivotCharts. XLSX export includes a native chart-to-pivot association. Removing the pivot leaves its chart as a static chart with the last displayed values.

Calculated Fields and Formulas
A calculated field evaluates a formula for each source record before aggregation. Refer to source fields in brackets. Add calculated fields in dependency order when one uses an earlier calculated field. This is a record calculation. Excel's classic calculated fields instead aggregate source fields before evaluating their formula, so division and multiplication can produce different results. Additive profit formulas such as Revenue minus Cost have the same result. These fields do not implement Excel Data Model measures or calculated pivot items.
pivot.update({
calculatedFields: [{ name: 'Profit', formula: '=[Revenue]-[Cost]' }],
values: [{ field: 'Profit', caption: 'Profit', numberFormatCode: '$#,##0.00' }]
});
report.cell('B12').setText('European profit');
report.cell('C12').setValue(pivot.getData('Profit', ['Europe']));
report.cell('C13').setFormula('=GETPIVOTDATA("Profit",B3,"Region","Europe")');
getData returns the underlying aggregate. Missing row/column intersections return null, while actual zero aggregates remain 0. The report shows blanks or your empty-cell caption for missing intersections, and connected charts retain gaps. Use getResult().cells for display calculations such as percentages. GETPIVOTDATA returns the visible report value, including Show Values As calculations and empty or error captions. Its reference can be a cell or range intersecting the report. Field/item pairs accept source names or axis captions and typed member values. A collapsed detail, filtered item or disabled subtotal/grand total returns #REF! when its intersection is no longer visible.
Refresh, Persistence and Output
Creation and settings changes refresh immediately. By default, editing source cells leaves the cached report unchanged until refresh() or workbook.pivotTables.refreshAll(). Setting autoRefresh: true joins source edits and pivot refresh in one undo transaction. This also observes source formulas whose dependencies are on another worksheet, resized source tables and changed named-range references. Connected charts and formulas update with the refreshed report. Drill-through, aggregates and member lists use the last refreshed data.
import { StreamType } from '@txtextcontrol/tx-sheet-control';
source.cell('C2').setValue(1500);
pivot.refresh();
const chart = pivot.createChart({ type: 'column-clustered', title: 'Regional Sales' });
pivot.update({ destination: { sheetId: report.id, cell: 'B20' } });
// The bound chart follows the report's new range.
const xlsx = await editor.save(StreamType.SpreadsheetML);
const pdf = await editor.save(StreamType.PDF);
TXWB preserves the complete definition, cached records and result cells. XLSX includes native worksheet PivotTable definitions, typed caches and linked PivotCharts, plus TX Sheet Control settings for features outside the native projection. PDF includes the materialized worksheet report. The native PivotChart association uses a worksheet PivotTable, without an Excel Data Model.
Excel and XLSX Compatibility
The editable native projection covers worksheet ranges, table and named sources, field axes, multiple measures, ordinary aggregations, standard display calculations, member/report filters and basic layout. Imported reports use their saved cache until you refresh, even when source cells contain newer values. Excel-authored field captions, value number formats, filter selections, first-level collapsed members and supported display flags are imported. Deeper native collapse and arbitrary manual member ordering are not fully projected; review their visible layout after import. An Excel save can update native settings while retaining older TX settings; PIVOT_EXTENSION_STALE then identifies that native settings and caches took precedence.
| Feature | Compatibility boundary |
|---|---|
| Ordinary worksheet PivotTables and PivotCharts | Export as native linked objects. Field/filter edits and refresh update the chart. Automatic refresh on opening the exported XLSX is disabled. |
| Grouping, record-level calculated fields, distinct counts, ranks and other unsupported display/filter calculations | Keep the worksheet/chart snapshot and full TX settings. Their exported native cache has refresh disabled, and unsupported measures are not substituted with Count or ordinary Sum. Reloading the unchanged file in TX Sheet Control reports PIVOT_NATIVE_SNAPSHOT and restores its complete programmable definition. |
| Excel calculated fields | Excel aggregates first; TX calculated fields evaluate each source record first. Ratios and products can differ. Native calculated-field and calculated-item imports are preserved with a projection warning rather than exposed as an editable approximation. |
| External, OLAP and Data Model sources, unsupported grouping or advanced native filter structures | Original package content is preserved by the XLSX document preservation API, with PIVOT_PROJECTION. These reports are not exposed as fully editable pivots. |
| Scatter, bubble and stock PivotCharts | Rejected, matching Excel's chart-family restrictions. Use an ordinary chart when these families are required. |
Editor and server-control saves retain the original XLSX package by default when preserveOriginal applies. Direct XlsxDocument.export also preserves unsupported native parts. A bare Workbook.load/save workflow creates a fresh modeled workbook and can include only the projected model. An Excel-edited advanced snapshot can remain preserved-only when the retained TX settings no longer match its native definition. Inspect load warnings and retain TXWB when complete TX behavior must remain editable.
remove({ keepValues: true }) converts a report into ordinary editable cells. Without that option, removal clears its result cells and formatting. Loading a different document invalidates old handles; acquire new ones from the loaded workbook. Partial row or column insertion/deletion through a report is rejected; insert before it or relocate it first.
Node.js, Angular and .NET
Node.js uses @txtextcontrol/tx-sheet-control-server and the same workbook collections, field options and synchronous pivot operations. Obtain the workbook from ServerSheetControl. Angular obtains the browser editor from its ready event and uses editor.workbook.pivotTables and editor.ui.pivotTables; it does not require a separate pivot package.
The NuGet package TXTextControl.TXSheetControl.Server exposes asynchronous operations with the same options:
using TXTextControl.TXSheetControl.Server;
await using var control = new ServerSheetControl();
var orders = await control.Workbook.Sheets.AtAsync(0);
await orders.Range("A1:C5").SetValuesAsync([
[],
[], ["Europe", "Services", 700],
[], ["Americas", "Services", 950]
]);
var target = await control.Workbook.Sheets.AddAsync("Sales Pivot");
var sales = await target.PivotTables.AddAsync(new PivotTableOptions {
Name = "RegionalSales",
Source = new() { SheetId = orders.Id, Range = "A1:C5" },
Destination = new() { SheetId = target.Id, Cell = "B3" },
Rows = [new() { Field = "Region" }],
Columns = [new() { Field = "Category" }],
Values = [new() { Field = "Revenue", Caption = "Sales", NumberFormatCode = "$#,##0.00" }]
});
await sales.UpdateAsync(new { layout = "tabular", repeatLabels = true });
await sales.SetFiltersAsync([new() { Field = "Region", Type = "include", Items = ["Europe"] }]);
await control.Workbook.SaveAsync("sales-pivot.xlsx", StreamType.SpreadsheetML);
await control.Workbook.SaveAsync("sales-pivot.pdf", StreamType.PDF);
Use camelCase anonymous objects for partial UpdateAsync patches. PivotTableOptions is a complete creation model; its initialized name, source and destination defaults make it unsuitable as a partial patch. In .NET result matrices, scalar objects deserialize as JsonElement; use GetDataAsync for numeric aggregates or inspect each scalar's JSON kind before converting it.
Limits and Validation
Each workbook supports at most 256 pivots, with an 8 MB serialized pivot-metadata budget including cached records and native layout metadata. Empty/error replacement text is limited to 1,024 characters. A source is limited to 100,000 records and 2,000,000 cells, with unique nonblank headers. Source and calculated fields together are limited to 1,024 fields; entirely blank source rows are skipped. A report supports 32 total axis fields, 64 value fields, 64 calculated fields and at most 200,000 output cells. Complex hierarchies also have an aggregation-work budget. Filter or group a large source rather than expanding an unbounded cross-tab.
Invalid settings, unknown fields, overlapping output and protected destinations fail atomically. The previous report remains intact. Pivot operations share workbook history and workbook events; batch related edits when they should form one undo step.
Run the Solution Samples
The Razor sample provides /PivotTables, with a 216-order source table, field pane, refresh, filters, details and download buttons. The console samples create reports through the public server API without opening an editor:
node samples/server/pivot-tables.mjs outputs/pivot-sample-node
dotnet run --project samples/server-dotnet/Server.Sample.csproj -- --pivot outputs/pivot-sample-dotnet
Each console sample writes XLSX, TXWB and PDF files plus the European source records as JSON. The samples belong to the solution; they do not add another public package.