# 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.

- **Author:** Bjoern Meyer
- **Published:** 2026-12-05
- **Modified:** 2026-12-04
- **Description:** 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.
- **8 min read** (1488 words)
- **Tags:**
  - JavaScript
  - TX Sheet Control
  - Excel
  - Spreadsheet
  - JavaScript Spreadsheet Essentials
- **Web URL:** https://www.textcontrol.com/blog/2026/12/05/how-to-create-pivot-tables-in-javascript/
- **LLMs URL:** https://www.textcontrol.com/blog/2026/12/05/how-to-create-pivot-tables-in-javascript/llms.txt
- **LLMs-Full URL:** https://www.textcontrol.com/blog/2026/12/05/how-to-create-pivot-tables-in-javascript/llms-full.txt

---

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)](https://s1-www.textcontrol.com/assets/dist/blog/2026/12/05/d/assets/javascript-pivot-tables.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.

![The sample PivotTable and its field pane: Region in Rows, Product in Columns, and Revenue in Values.](https://s1-www.textcontrol.com/assets/dist/blog/2026/12/05/d/assets/sample.webp "The sample PivotTable and its field pane: Region in Rows, Product in Columns, and Revenue in Values.") The sample PivotTable and its field pane: Region in Rows, Product in Columns, and Revenue in Values.

### 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.

![The Europe filter narrows the PivotTable without deleting source rows.](https://s1-www.textcontrol.com/assets/dist/blog/2026/12/05/d/assets/pivot-tables-filtered.webp "The Europe filter narrows the PivotTable without deleting source rows.") The Europe filter narrows the PivotTable without deleting source rows.

### 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](https://docs.textcontrol.com/tx-sheet-control/spreadsheets/pivot-tables/).

[Previous: How to Export JSON Data to Excel in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-export-json-data-to-excel-in-javascript/llms-full.txt)  
[Next: How to Apply Conditional Formatting in a JavaScript Spreadsheet](https://www.textcontrol.com/blog/2026/12/05/how-to-apply-conditional-formatting-in-a-javascript-spreadsheet/llms-full.txt)

JavaScript Spreadsheet Essentials · Part 4 of 8

1. [How to Import, Edit, and Export Excel XLSX Files in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-import-edit-and-export-excel-xlsx-files-in-javascript/llms-full.txt)
2. [How to Convert Excel to PDF in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-convert-excel-to-pdf-in-javascript/llms-full.txt)
3. [How to Export JSON Data to Excel in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-export-json-data-to-excel-in-javascript/llms-full.txt)
4. How to Create Pivot Tables in JavaScript
5. [How to Apply Conditional Formatting in a JavaScript Spreadsheet](https://www.textcontrol.com/blog/2026/12/05/how-to-apply-conditional-formatting-in-a-javascript-spreadsheet/llms-full.txt)
6. [How to Create an ODS File in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-an-ods-file-in-javascript/llms-full.txt)
7. [How to Create an Excel XLSX File in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-an-excel-xlsx-file-in-javascript/llms-full.txt)
8. [How to Load REST API Data into a JavaScript Spreadsheet](https://www.textcontrol.com/blog/2026/12/05/how-to-load-rest-api-data-into-a-javascript-spreadsheet/llms-full.txt)

### Frequently Asked Questions

Does XLSX contain a real Excel PivotTable? 
-------------------------------------------

This sample uses a supported worksheet source, ordinary Sum aggregation, and a member filter. It exports as a native Excel PivotTable.

Do source edits automatically update the report? 
-------------------------------------------------

This example refreshes explicitly with pivot.refresh(). Refresh rereads the source and regenerates the result.

Does filtering remove sales records? 
-------------------------------------

No. The PivotTable filter changes the report while leaving source worksheet records intact.

---

## About Bjoern Meyer

As CEO, Bjoern is the visionary behind our strategic direction and business development, bridging the gap between our customers and engineering teams. His deep passion for coding and web technologies drives the creation of innovative products. If you're at a tech conference, be sure to stop by our booth - you'll most likely meet Bjoern in person. With an advanced graduate degree (Dipl. Inf.) in Computer Science, specializing in AI, from the University of Bremen, Bjoern brings significant expertise to his role. In his spare time, Bjoern enjoys running, paragliding, mountain biking, and playing the piano.

- [LinkedIn](https://www.linkedin.com/in/bjoernmeyer/)
- [X](https://x.com/txbjoern)
- [GitHub](https://github.com/bjoerntx)

---

## Series

- [How to Import, Edit, and Export Excel XLSX Files in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-import-edit-and-export-excel-xlsx-files-in-javascript/llms.txt)
- [How to Convert Excel to PDF in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-convert-excel-to-pdf-in-javascript/llms.txt)
- [How to Export JSON Data to Excel in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-export-json-data-to-excel-in-javascript/llms.txt)
- **How to Create Pivot Tables in JavaScript** (this article)
- [How to Apply Conditional Formatting in a JavaScript Spreadsheet](https://www.textcontrol.com/blog/2026/12/05/how-to-apply-conditional-formatting-in-a-javascript-spreadsheet/llms.txt)
- [How to Create an ODS File in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-an-ods-file-in-javascript/llms.txt)
- [How to Create an Excel XLSX File in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-an-excel-xlsx-file-in-javascript/llms.txt)
- [How to Load REST API Data into a JavaScript Spreadsheet](https://www.textcontrol.com/blog/2026/12/05/how-to-load-rest-api-data-into-a-javascript-spreadsheet/llms.txt)

---

## Related Posts

- [How to Load REST API Data into a JavaScript Spreadsheet](https://www.textcontrol.com/blog/2026/12/05/how-to-load-rest-api-data-into-a-javascript-spreadsheet/llms.txt)
- [How to Create an Excel XLSX File in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-an-excel-xlsx-file-in-javascript/llms.txt)
- [How to Create an ODS File in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-an-ods-file-in-javascript/llms.txt)
- [How to Apply Conditional Formatting in a JavaScript Spreadsheet](https://www.textcontrol.com/blog/2026/12/05/how-to-apply-conditional-formatting-in-a-javascript-spreadsheet/llms.txt)
- [How to Export JSON Data to Excel in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-export-json-data-to-excel-in-javascript/llms.txt)
- [How to Convert Excel to PDF in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-convert-excel-to-pdf-in-javascript/llms.txt)
- [How to Import, Edit, and Export Excel XLSX Files in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-import-edit-and-export-excel-xlsx-files-in-javascript/llms.txt)
- [Inside the TX Sheet Control Spreadsheet Editor: A Complete Spreadsheet for Your Web Applications](https://www.textcontrol.com/blog/2026/12/01/inside-the-tx-sheet-control-spreadsheet-editor/llms.txt)
- [TX Sheet Control 2.0 Is Now Available: Spreadsheets and Dashboards for Your Applications](https://www.textcontrol.com/blog/2026/12/01/tx-sheet-control-2-0-is-now-available/llms.txt)
