How to Create Pivot Tables in JavaScript
Create a JavaScript PivotTable from sales records with TX Sheet Control. Configure row and column fields, sum revenue, filter regions, refresh source edits, and export a native Excel PivotTable.

Summarize sales revenue by region and product with a PivotTable in JavaScript. TX Sheet Control creates the cross-tab in a worksheet, exposes its field list in the editor, and exports supported reports as native Excel PivotTables.
Part 4 of the JavaScript Spreadsheet Essentials series.
Run the JavaScript Sample
This example uses TX Sheet Control 2.0.0 with plain JavaScript. Download the complete sample and output files (ZIP). Extract it and open its sample folder.
Copy the complete browser folder from your TX Sheet Control download into sample/public/sheet, retaining its fonts, languages, and notices. Put your signed tx-sheet-control.license beside server.mjs. Use Node.js 22 or later to run the included local host:
npm start
Open http://127.0.0.1:5085. The host serves the files; workbook editing and conversion run in the browser. The HTML supplies the editor host and loads /sheet/tx-sheet-control.min.js followed by app.js.
The shared common.js module creates the editor, awaits its fonts and initial readiness, manages progress messages, and delivers byte downloads:
export const { Spreadsheet, StreamType } = TXTextControl.TXSheetControl;
export const status = document.getElementById('status');
export async function createEditor() {
const response = await fetch('/license', {cache:'no-store'});
if (!response.ok) throw new Error('Configure tx-sheet-control.license before starting the sample.');
const editor = new Spreadsheet(document.getElementById('sheet'), {
license: (await response.text()).trim(),
fontCatalogURL: '/sheet/fonts/catalog.json',
fontBaseURL: '/sheet/fonts/', locale:'en-US', currency:'USD'
});
await editor.ready;
return editor;
}
export function download(bytes, name, mime) {
const url = URL.createObjectURL(new Blob([bytes], {type:mime}));
const link = document.createElement('a');
link.href=url; link.download=name;
document.body.append(link); link.click(); link.remove();
setTimeout(()=>URL.revokeObjectURL(url),5000);
}
export function showWarnings(warnings) {
const list=document.getElementById('diagnostics');
list.replaceChildren();
const messages=warnings.length ? warnings.map(w=>typeof w==='string' ? w : w.message ?? JSON.stringify(w))
: ['No conversion warnings.'];
for(const message of messages) {
const item=document.createElement('li'); item.textContent=message; list.append(item);
}
}
export async function busy(message, action) {
const buttons=[...document.querySelectorAll('button,input[type=file]')];
buttons.forEach(button=>button.disabled=true);
status.textContent=message;
try { return await action(); }
catch(error) { status.textContent=error.message; throw error; }
finally { buttons.forEach(button=>button.disabled=false); }
}
Prepare Sales Records with Headers
The sample starts with the same six-order sales report used throughout this series. Its source rectangle is A4:H10 on the Sales worksheet. Headers are unique and identify fields such as Region, Product, and Revenue.
The source Revenue cells contain formulas. The PivotTable aggregates their calculated numeric values. Keep labels and quantities in separate columns, and avoid blank or duplicate field names.
Choose Rows, Columns, and Values
Create a separate worksheet for the report. rows groups records by Region, columns groups them by Product, and values sums Revenue. The result begins at B4:
import {sales,writeSales} from './sales.js';
export function build(workbook) {
const source=workbook.sheets.at(0);
source.rename('Sales');
const {lastRow}=writeSales(source,sales);
const report=workbook.sheets.add('Revenue by Region');
report.cell('B1').setText('REVENUE BY REGION AND PRODUCT');
report.cell('B1').format({fontSize:18,bold:true,textColor:'#762060'});
const pivot=report.pivotTables.add({
name:'RegionalRevenue',
source:{sheetId:source.id,range:`A4:H${lastRow}`},
destination:{sheetId:report.id,cell:'B4'},
rows:[{field:'Region'}],
columns:[{field:'Product'}],
values:[{field:'Revenue',caption:'Revenue',aggregation:'sum',numberFormatCode:'$#,##0.00'}],
layout:'tabular',style:{name:'TableStyleMedium2',rowBanding:true}
});
[30,200,140,140,140].forEach((pixels,index)=>report.columns.at(index).setWidth({pixels}));
return {source,report,pivot};
}
export function filterEurope(pivot) {
pivot.setFilters([{field:'Region',type:'include',items:['Europe']}]);
}
export function refreshRevenue(source,pivot) {
source.cell('D5').setValue(10);
pivot.refresh();
return pivot.getData('Revenue',[]);
}
aggregation: 'sum' makes the measure explicit. numberFormatCode formats the result as currency. The tabular layout and banded style make it easier to follow a row across its product totals.
The initial report shows Americas at $2,550, Asia Pacific at $1,150, and Europe at $1,700. Its grand total is $5,400. The destination must have enough space and must not overlap source data or unrelated worksheet content.
Filter the Report
filterEurope() calls setFilters() with an include filter. It leaves the source records in place while showing only Europe's $1,700 in revenue. Passing an empty filter array restores all regions.
Refresh After a Source Edit
refreshRevenue() changes the first order from eight units to ten and calls pivot.refresh(). The first order grows from $1,000 to $1,250, Europe becomes $1,950, and the unfiltered grand total becomes $5,650.
Refresh rereads the source and rewrites the PivotTable result. Edit the source records rather than typing into materialized result cells. For growing operational data, use a table or named-range source and refresh against its current extent.
Connect the Field List and Buttons
editor.ui.pivotTables.show(pivot) activates the report and opens the field pane. Users can move fields between areas, change aggregation, and use the contextual PivotTable ribbon. The application adds Filter, Show all, Refresh, and Download actions:
import {createEditor,StreamType,download,busy,showWarnings,status} from './common.js';
import {build,filterEurope,refreshRevenue} from './model.js';
async function start(){
const editor=await createEditor();
const actions={};let model={};
const addAction=(id,label,action)=>{
actions[id]=action;const button=document.createElement('button');button.id=id;button.textContent=label;
button.addEventListener('click',()=>busy('Working…',action).catch(()=>{}));
document.getElementById('actions').append(button);
};
const downloadXlsx=async()=>{
const bytes=await editor.save(StreamType.SpreadsheetML);
showWarnings(editor.getXlsxWarnings());
download(bytes,'pivot-tables.xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
status.textContent='Workbook exported successfully. Review conversion diagnostics.';
};
model=build(editor.workbook);
editor.ui.pivotTables.show(model.pivot);
addAction('filter','Filter Europe',async()=>{filterEurope(model.pivot);status.textContent='Europe revenue: $1,700.00.';});
addAction('clear','Show all regions',async()=>{model.pivot.setFilters([]);status.textContent='All regions · Revenue: '+model.pivot.getData('Revenue',[]);});
addAction('refresh','Change source and refresh',async()=>{const total=refreshRevenue(model.source,model.pivot);status.textContent='Source changed to 10 units; refreshed revenue: '+total;});
addAction('export','Download pivot XLSX',downloadXlsx);
status.textContent='Revenue by region and product · Grand total: $5,400.00.';
return {editor,actions,get model(){return model;}};
}
window.sampleReady=start();
window.sampleReady.catch(error=>{status.textContent=error.message;console.error(error);});
Export and Refresh in Excel
Save with StreamType.SpreadsheetML. Open the downloaded workbook in Excel, select the Revenue by Region worksheet, and click inside the report. Excel recognizes the native PivotTable and displays its PivotTable controls.
Change Sales!D5 to 10 and refresh the PivotTable in Excel. The sample was checked with Excel: the native report changed from $5,400 to $5,650. Automatic refresh on opening the exported file is disabled, so choose Refresh when you want to reread the source.
This example uses ordinary sums and member filtering. Advanced grouping, record-level calculated fields, or other unsupported native calculations can require a snapshot projection. Inspect conversion warnings and retain TXWB when you need the full TX definition.
Read more in the TX Sheet Control documentation.
Previous: How to Export JSON Data to Excel in JavaScript
Next: How to Apply Conditional Formatting in a JavaScript Spreadsheet
JavaScript Spreadsheet Essentials · Part 4 of 8
- How to Import, Edit, and Export Excel XLSX Files in JavaScript
- How to Convert Excel to PDF in JavaScript
- How to Export JSON Data to Excel in JavaScript
- How to Create Pivot Tables in JavaScript
- How to Apply Conditional Formatting in a JavaScript Spreadsheet
- How to Create an ODS File in JavaScript
- How to Create an Excel XLSX File in JavaScript
- How to Load REST API Data into a JavaScript Spreadsheet
Frequently Asked Questions
This sample uses a supported worksheet source, ordinary Sum aggregation, and a member filter. It exports as a native Excel PivotTable.
This example refreshes explicitly with pivot.refresh(). Refresh rereads the source and regenerates the result.
No. The PivotTable filter changes the report while leaving source worksheet records intact.
Jump to the other posts in this series:
- How to Import, Edit, and Export Excel XLSX Files in JavaScript
- How to Convert Excel to PDF in JavaScript
- How to Export JSON Data to Excel in JavaScript
- How to Create Pivot Tables in JavaScript
- How to Apply Conditional Formatting in a JavaScript Spreadsheet
- How to Create an ODS File in JavaScript
- How to Create an Excel XLSX File in JavaScript
- How to Load REST API Data into a JavaScript Spreadsheet
TX Sheet Control
Excel-compatible spreadsheet editing, a robust calculation engine, and interactive dashboards for business applications.
Related Posts
JavaScriptExcelJavaScript Spreadsheet Essentials
How to Load REST API Data into a JavaScript Spreadsheet
Fetch REST API JSON into a JavaScript spreadsheet with TX Sheet Control. Validate and map records, show loading and error states, refresh data, and update dependent formulas.
JavaScriptExcelJavaScript Spreadsheet Essentials
How to Create an Excel XLSX File in JavaScript
Create an Excel XLSX file from scratch in JavaScript. Add worksheets, write typed data and formulas, format headers and currency, set column widths, and download the workbook.
JavaScriptExcelJavaScript Spreadsheet Essentials
How to Create an ODS File in JavaScript
Create an ODS workbook in JavaScript with text, numbers, formulas, and currency formatting. Download it, reopen it in TX Sheet Control, and check its standard spreadsheet content in LibreOffice Calc.
JavaScriptExcelJavaScript Spreadsheet Essentials
How to Apply Conditional Formatting in a JavaScript Spreadsheet
Apply conditional formatting in a JavaScript spreadsheet: highlight overdue invoices and negative margins, add revenue data bars and target color scales, and update the rules through cell edits.
JavaScriptExcelJavaScript Spreadsheet Essentials
How to Export JSON Data to Excel in JavaScript
Export JSON records to a formatted Excel workbook in JavaScript. Map fields, retain numeric values, format dates and currency, calculate totals, and download XLSX.
