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

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

---

Build an Excel workbook in the browser with JavaScript and TX Sheet Control. This example creates Sales, Summary, and Notes worksheets, formats the sales report, links totals between sheets, and downloads the result as XLSX.

Part 7 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/g/assets/javascript-create-xlsx.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); }
}
```

### Populate the Sales Worksheet

The first worksheet contains six orders. The shared sales helper writes the title, header row, numeric dates, and sales inputs, then adds revenue, margin, and SUM formulas:

```
export const sales = [
    { date:'2026-11-02', region:'Europe', product:'Software', units:8, unitPrice:125, cost:700 },
    { date:'2026-11-04', region:'Europe', product:'Services', units:4, unitPrice:175, cost:420 },
    { date:'2026-11-07', region:'Americas', product:'Software', units:12, unitPrice:125, cost:900 },
    { date:'2026-11-10', region:'Americas', product:'Services', units:6, unitPrice:175, cost:650 },
    { date:'2026-11-14', region:'Asia Pacific', product:'Software', units:5, unitPrice:125, cost:500 },
    { date:'2026-11-18', region:'Asia Pacific', product:'Services', units:3, unitPrice:175, cost:300 }
];

export function toExcelDate(isoDate, dateSystem = '1900') {
    if (typeof isoDate !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(isoDate))
        throw new Error('Use an ISO date in YYYY-MM-DD format.');
    const utc = Date.parse(isoDate + 'T00:00:00Z');
    if (!Number.isFinite(utc) || new Date(utc).toISOString().slice(0,10) !== isoDate)
        throw new Error('Invalid calendar date.');
    // The sample uses modern dates, after Excel's historical 1900 leap-day boundary.
    const epoch = dateSystem === '1904' ? Date.UTC(1904,0,1) : Date.UTC(1899,11,30);
    return (utc - epoch) / 86400000;
}

export function validateSales(records) {
    if (!Array.isArray(records) || records.length === 0 || records.length > 1000)
        throw new Error('Expected between 1 and 1000 sales records.');
    return records.map(record => {
        if (!record || typeof record.region !== 'string' || !record.region.trim() ||
            typeof record.product !== 'string' || !record.product.trim())
            throw new Error('Each record needs a region and product.');
        for (const field of ['units','unitPrice','cost']) {
            if (typeof record[field] !== 'number' || !Number.isFinite(record[field]) || record[field] < 0)
                throw new Error('Sales amounts must be finite nonnegative numbers.');
        }
        toExcelDate(record.date);
        return {...record};
    });
}

export function writeSales(sheet, records) {
    const rows = validateSales(records);
    const lastRow = rows.length + 4;
    const totalRow = lastRow + 2;
    sheet.range('A1:H1006').clear();
    sheet.cell('A1').setText('NORTHSTAR / SALES REPORT');
    sheet.range('A1:H1').merge();
    sheet.cell('A2').setText('November 2026 · Revenue, costs and margin · USD');
    sheet.range('A4:H4').setValues([['Date','Region','Product','Units','Unit price','Revenue','Cost','Margin']]);
    sheet.range(`A5:H${lastRow}`).setValues(rows.map(record => [
        toExcelDate(record.date, sheet.workbook.dateSystem), record.region, record.product,
        record.units, record.unitPrice, null, record.cost, null
    ]));
    rows.forEach((_,index) => {
        const row = index + 5;
        sheet.cell(`F${row}`).setFormula(`=D${row}*E${row}`);
        sheet.cell(`H${row}`).setFormula(`=F${row}-G${row}`);
    });
    sheet.cell(`A${totalRow}`).setText('TOTAL');
    for (const column of ['D','F','G','H'])
        sheet.cell(`${column}${totalRow}`).setFormula(`=SUM(${column}5:${column}${lastRow})`);
    sheet.range('A1:H1').format({fontSize:18,bold:true,textColor:'#762060'});
    sheet.range('A4:H4').format({bold:true,fillColor:'#762060',textColor:'#ffffff'});
    sheet.range(`E5:H${totalRow}`).format({numberFormatCode:'$#,##0.00'});
    sheet.range(`A5:A${lastRow}`).format({numberFormatCode:'yyyy-mm-dd'});
    sheet.range(`A${totalRow}:H${totalRow}`).format({bold:true,fillColor:'#f6e8f3'});
    [112,140,130,70,115,120,110,110].forEach((pixels,index)=>sheet.columns.at(index).setWidth({pixels}));
    sheet.rows.at(0).setHeight({pixels:34});
    sheet.rows.at(3).setHeight({pixels:28});
    return {lastRow,totalRow,count:rows.length};
}
```

`setValues()` accepts a matrix whose dimensions match the target range. The mapping explicitly orders Date, Region, Product, Units, Unit price, Revenue, Cost, and Margin. Values and formulas use separate calls so their meaning is clear.

### Add Summary and Notes Worksheets

`workbook.sheets.add()` creates the additional worksheets and returns stable handles. The Summary worksheet uses qualified formulas to reference the Sales total row:

```
import {sales,writeSales} from './sales.js';

export function build(workbook) {
    const sheet=workbook.sheets.at(0);
    sheet.rename('Sales');
    const result=writeSales(sheet,sales);
    const summary=workbook.sheets.add('Summary');
    summary.range('A1:B4').setValues([
        ['SALES SUMMARY','USD'],['Revenue',null],['Cost',null],['Margin',null]
    ]);
    summary.cell('B2').setFormula(`='Sales'!F${result.totalRow}`);
    summary.cell('B3').setFormula(`='Sales'!G${result.totalRow}`);
    summary.cell('B4').setFormula('=B2-B3');
    summary.range('A1:B1').format({bold:true,fillColor:'#762060',textColor:'#ffffff'});
    summary.range('B2:B4').format({numberFormatCode:'$#,##0.00'});
    summary.columns.at(0).setWidth({pixels:220});
    summary.columns.at(1).setWidth({pixels:150});
    const notes=workbook.sheets.add('Notes');
    notes.cell('A1').setText('Amounts are in USD. Edit Sales to update Summary.');
    notes.columns.at(0).setWidth({pixels:520});
    return {sheet,summary,...result};
}
```

The formula in Summary!B2 references Sales!F12, and B3 references its cost total. B4 subtracts cost from revenue. The resulting amounts are $5,400, $3,470, and $1,930. The Notes worksheet records that amounts are in USD.

![The newly created Sales worksheet, with Summary and Notes available in the workbook tabs.](https://s1-www.textcontrol.com/assets/dist/blog/2026/12/05/g/assets/sample.webp "The newly created Sales worksheet, with Summary and Notes available in the workbook tabs.") The newly created Sales worksheet, with Summary and Notes available in the workbook tabs.

### Format Headers, Currency, and Column Widths

The helper applies a purple header fill, white header text, a larger title, and a pale total row. Currency uses `numberFormatCode: '$#,##0.00'`, while dates use `yyyy-mm-dd`. These are display rules over numeric values.

`sheet.columns.at(index).setWidth({ pixels })` sets deliberate widths. Column indices are zero-based. The report leaves enough room for region names, currency values, and the date format instead of relying on a narrow default width.

### Update Linked Calculations

Select Summary in the sample to inspect its formulas and totals. Change a Sales quantity or price to update revenue and margin, then return to Summary to see the linked result.

![The Summary worksheet reads its totals through formulas linked to Sales.](https://s1-www.textcontrol.com/assets/dist/blog/2026/12/05/g/assets/create-xlsx-summary.webp "The Summary worksheet reads its totals through formulas linked to Sales.") The Summary worksheet reads its totals through formulas linked to Sales.

Accessing a worksheet through the API does not activate it in the editor. The Show Sales and Show Summary actions use `editor.ui.selectSheet()` to change the visible worksheet deliberately.

### Download the Excel File

The application saves with `StreamType.SpreadsheetML` and offers the returned bytes as an XLSX Blob. The full button wiring is shown here:

```
import {createEditor,StreamType,download,busy,showWarnings,status} from './common.js';
import {build} 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,'create-xlsx.xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  status.textContent='Workbook exported successfully. Review conversion diagnostics.';
 };
 model=build(editor.workbook);
 addAction('summary','Show Summary',async()=>{editor.ui.selectSheet(model.summary);status.textContent='Summary formulas link to the Sales worksheet.';});
 addAction('sales','Show Sales',async()=>{editor.ui.selectSheet(model.sheet);status.textContent='Six sales orders. Edit a value to update the formulas.';});
 addAction('export','Download workbook XLSX',downloadXlsx);
 status.textContent='Three worksheets created: Sales, Summary and Notes. Revenue: $5,400.00.';
 return {editor,actions,get model(){return model;}};
}
window.sampleReady=start();
window.sampleReady.catch(error=>{status.textContent=error.message;console.error(error);});
```

After saving, check conversion diagnostics and open the output in Excel. Verify that all three worksheet tabs are present, that Summary references Sales, and that currency and dates retain their intended display. The sample workbook was opened in Excel and its $5,400 revenue total checked.

For larger reports, keep column mapping and formatting in reusable functions, and write ranges in batches. The downloadable sample includes the complete HTML, JavaScript modules, data, and local host.

Read more in the [TX Sheet Control documentation](https://docs.textcontrol.com/tx-sheet-control/document-processing/load-save/).

[Previous: 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)  
[Next: 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)

JavaScript Spreadsheet Essentials · Part 7 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](https://www.textcontrol.com/blog/2026/12/05/how-to-create-pivot-tables-in-javascript/llms-full.txt)
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
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

Can a browser-created XLSX contain several worksheets? 
-------------------------------------------------------

Yes. Create worksheets with workbook.sheets.add and populate each returned worksheet handle.

How do I link values between worksheets? 
-----------------------------------------

Use qualified formulas such as ='Sales'!F12. The sample Summary worksheet links to Sales totals.

Does currency formatting turn numbers into text? 
-------------------------------------------------

No. A number format changes the display while keeping numeric values available for calculation.

---

## 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](https://www.textcontrol.com/blog/2026/12/05/how-to-create-pivot-tables-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 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** (this article)
- [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 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 Create Pivot Tables in JavaScript](https://www.textcontrol.com/blog/2026/12/05/how-to-create-pivot-tables-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 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)
