Excel Engine overviewExcel
A self-contained xlsx writer and reader for browsers, Web Workers and Node, with styles, number formats, freeze panes, outlines and merges.
The Birch UI Excel Engine, @birchui/excel, writes and reads native .xlsx files in plain TypeScript. It has no third-party dependencies, needs no server, and runs anywhere modern JavaScript runs: in the browser, in a Web Worker and in Node 20 or later. It powers Grid Pro's Excel export, and you can use it on its own for reports, data exchange and test fixtures.
Loading demo…
View source
Sample data and small UI helpers are imported from the docs' demos/_shared.ts and demos/_scheduler-data.ts files.
import { createGrid, type ColumnDef } from '@birchui/core';
import { AggregationModule, ExcelModule, RowGroupingModule } from '@birchui/grid-pro';
import {
button,
docsTheme,
formatCurrency,
layout,
makeOrders,
onDocsThemeChange,
revenueOf,
type Order,
} from './_shared';
export const meta = { title: 'Excel export and import', height: 480 };
const columns: ColumnDef<Order>[] = [
{ field: 'region', header: 'Region', rowGroup: true },
{ field: 'id', header: 'Order', width: 110 },
{ field: 'customer', header: 'Customer', width: 190 },
{ field: 'product', header: 'Product', width: 180 },
{ field: 'quantity', header: 'Units', type: 'number', width: 90, aggFunc: 'sum' },
{
id: 'revenue',
header: 'Revenue',
type: 'number',
width: 130,
valueGetter: revenueOf,
format: formatCurrency,
aggFunc: 'sum',
},
{ field: 'orderDate', header: 'Ordered', type: 'date', width: 120 },
];
export default function mount(el: HTMLElement): () => void {
const { toolbar, body, status } = layout(el);
const grid = createGrid<Order>(body, {
columns,
rows: makeOrders(1200, 33),
getRowId: (order) => order.id,
modules: [RowGroupingModule, AggregationModule, ExcelModule],
groupDefaultExpanded: 1,
rowSelection: 'multiple',
theme: docsTheme(),
ariaLabel: 'Orders ready for Excel export',
});
const run = async (task: () => Promise<unknown> | undefined, done: string) => {
try {
await task();
status.textContent = done;
} catch (error) {
status.textContent = `Export failed: ${(error as Error).message}`;
}
};
const file = document.createElement('input');
file.type = 'file';
file.accept = '.xlsx';
file.hidden = true;
const onFile = () => {
const chosen = file.files?.[0];
if (!chosen) return;
run(() => grid.importExcel?.(chosen), `Imported ${chosen.name}: ${grid.getRows().length.toLocaleString()} rows.`);
file.value = '';
};
file.addEventListener('change', onFile);
toolbar.append(
button('Download orders.xlsx', () =>
run(
() => grid.exportExcel?.({ fileName: 'orders-2026.xlsx', sheetName: 'Orders' }),
'Downloaded orders-2026.xlsx with the grouped view.',
),
),
button('Export selected rows', () =>
run(
() => grid.exportExcel?.({ fileName: 'selected-orders.xlsx', sheetName: 'Selected', onlySelected: true }),
'Downloaded selected-orders.xlsx.',
),
),
button('Import .xlsx', () => file.click()),
file,
);
status.textContent = grid.exportExcel
? 'The workbook keeps the grouped view, number formats and column widths.'
: 'ExcelModule is not installed.';
const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
return () => {
file.removeEventListener('change', onFile);
stopTheme();
grid.destroy();
};
}What it does#
Writing
- Strings, numbers, booleans, dates and formulas with cached results
- Cell, row and column styles: fonts, fills, borders, alignment, wrapping and indentation
- Built-in and custom number formats, including currency, percentages and dates
- Column widths, row heights, hidden rows and columns
- Freeze panes, autofilter, merged cells, outline levels for grouped rows and columns
- Several sheets per workbook, tab colours, right-to-left sheets and document properties
- Shared strings for compact files, DEFLATE compression through the platform's
CompressionStream
Reading
- Every sheet as a 2D array of values, with merged ranges
- Shared strings, inline strings and rich text
- Numbers, booleans, error values, cached formula results and ISO dates
- Dates recognised from their number format, in both the 1900 and 1904 date systems
sheetToObjects()turns a sheet into records keyed by its header row
Install#
npm install @birchui/excelThe package is ESM only, has no side effects on import and touches no browser globals until you call a function that needs them, so it is safe to import in server-rendered code.
Write a workbook#
import { downloadXlsx, type XlsxWorkbook } from '@birchui/excel';
const header = { bold: true, fill: '#1F3A5F', color: '#FFFFFF' };
const money = { numFmt: '"$"#,##0.00' };
const workbook: XlsxWorkbook = {
creator: 'Northwind Analytics',
sheets: [
{
name: 'Q3 revenue',
columns: [{ width: 18 }, { width: 14 }, { width: 14, style: money }, { width: 12 }],
freeze: { rows: 1 },
autoFilter: true,
rows: [
[
{ value: 'Region', style: header },
{ value: 'Closed on', style: header },
{ value: 'Revenue', style: header },
{ value: 'Deals', style: header },
],
['EMEA', new Date(Date.UTC(2026, 8, 30)), 1284500.5, 212],
['North America', new Date(Date.UTC(2026, 8, 30)), 1932040, 305],
['APAC', new Date(Date.UTC(2026, 8, 29)), 846210.75, 148],
['LATAM', new Date(Date.UTC(2026, 8, 28)), 402300, 77],
[
{ value: 'Total', style: { bold: true } },
null,
{ value: { formula: 'SUM(C2:C5)', value: 4465051.25 }, style: { bold: true } },
{ value: { formula: 'SUM(D2:D5)', value: 742 }, style: { bold: true } },
],
],
},
],
};
await downloadXlsx(workbook, 'q3-revenue.xlsx');Rows can be plain arrays of values, as above, or row objects with a height, an outline level or a style. Dates get the yyyy-mm-dd format automatically, and the money style on the third column applies to every cell in it.
Read a workbook#
import { readXlsx, sheetToObjects } from '@birchui/excel';
const input = document.querySelector<HTMLInputElement>('#price-list')!;
input.addEventListener('change', async () => {
const file = input.files?.[0];
if (!file) return;
const { sheets } = await readXlsx(file);
const products = sheetToObjects(sheets[0]);
console.table(products);
});readXlsx() accepts a Blob or File, an ArrayBuffer or a Uint8Array, and resolves to every sheet's values. See Reading files.
License key#
The engine verifies your key offline, in the same way as the other Birch UI products: no network calls and no activation server. Keys for the Excel Engine, Grid Pro, Pivot Studio, Spreadsheet and the Complete bundle all cover it.
Set the key once at startup with setLicenseKey(), and every Excel Engine call on the page uses it:
import { setLicenseKey } from '@birchui/license';
setLicenseKey(import.meta.env.VITE_BIRCHUI_LICENSE_KEY);Or pass it to a single call with the licenseKey option, which takes precedence over the global key:
const bytes = await writeXlsx(workbook, { licenseKey: process.env.BIRCHUI_LICENSE_KEY });
const imported = await readXlsx(file, { licenseKey: process.env.BIRCHUI_LICENSE_KEY });writeXlsx, writeXlsxSync, downloadXlsx and readXlsx accept licenseKey; the zip and cell helpers need no key. The check runs once per key per page and never delays or blocks a call. Without a covering key, the page logs a single warning, including on localhost, so you notice a missing key before you deploy. Call setLicenseKey() before the first export, otherwise that warning is logged before the key arrives.
A Web Worker or a Node process has its own copy of the license module, so call setLicenseKey() there too, or pass licenseKey; see Running in a worker.
Where it runs#
| Function | Browser page | Web Worker | Node 20+ |
|---|---|---|---|
writeXlsx(), writeXlsxSync() |
Yes | Yes | Yes |
readXlsx() |
Yes | Yes | Yes |
downloadXlsx() |
Yes | No, needs document |
No |
zip(), zipSync(), unzip() |
Yes | Yes | Yes |
Compression uses the standard CompressionStream and DecompressionStream APIs, available in current browsers, workers and Node. Where compression is unavailable, writeXlsx() writes an uncompressed but valid file. Reading compressed files, which is nearly every file saved by a spreadsheet application, needs DecompressionStream.
For large exports, run the writer in a Web Worker so the page stays responsive.
Problems are reported, not thrown#
Inputs that Excel would reject, such as an invalid colour, an overlapping merge range or text longer than 32,767 characters, are fixed or skipped. The engine collects these and logs them in a single console.warn per file, prefixed with [@birchui/excel]. It throws only when a file cannot be produced at all, for example when a sheet has more than 1,048,576 rows.
Guides#
- Writing workbooks: the workbook, sheet, row and cell model.
- Styles and number formats: fonts, fills, borders, alignment and formats.
- Freeze panes, outlines and merges: sheet layout features.
- Reading files: values, dates and records.
- Running in a worker: keeping the page responsive, and Node usage.
- Utilities: cell references, date serials and zip helpers.
- API reference.