Writing workbooksExcel
The workbook, sheet, row and cell model of the Excel Engine, and the writeXlsx, writeXlsxSync and downloadXlsx functions.
A workbook is a plain object. You describe sheets, rows and cells as data, and one function call turns it into the bytes of an .xlsx file. There are no classes to instantiate and no mutable builder state, so a workbook can be built in a worker, serialized as JSON (apart from Date values) or produced by a server.
The three write functions#
| Function | Returns | Use it when |
|---|---|---|
writeXlsx(workbook, options?) |
Promise<Uint8Array> |
You want the bytes: to upload, store, post from a worker or write to disk. Compressed by default. |
writeXlsxSync(workbook, options?) |
Uint8Array |
You need a synchronous result, for example in a test or a CLI. The file is valid but uncompressed, so it is larger. |
downloadXlsx(workbook, fileName, options?) |
Promise<void> |
You are on a web page and want the browser to download the file. Adds .xlsx to the name if missing. |
The options are:
| Option | Accepted by | Effect |
|---|---|---|
compress |
writeXlsx, downloadXlsx |
false writes an uncompressed file. Default true. |
licenseKey |
all three | Your license key for this call. Without it, the key from setLicenseKey() is used. See License key. |
import { writeXlsx, writeXlsxSync, downloadXlsx } from '@birchui/excel';
const bytes = await writeXlsx(workbook);
const uncompressed = await writeXlsx(workbook, { compress: false });
const sameBytesSync = writeXlsxSync(workbook, { licenseKey: process.env.BIRCHUI_LICENSE_KEY });
await downloadXlsx(workbook, 'invoices-2026-10');writeXlsx compresses with the platform's CompressionStream and falls back to an uncompressed file where that API is missing. downloadXlsx throws when there is no document, for example in a worker or in Node; use writeXlsx there and handle the bytes yourself.
Workbook#
const workbook: XlsxWorkbook = {
title: 'Field service report, October 2026',
creator: 'Fleetwise Operations',
created: new Date(),
sheets: [jobsSheet, techniciansSheet],
};title and creator are stored as document properties, which Excel shows under File › Info. A workbook without sheets is written with one empty sheet named Sheet1. The first sheet is the one selected when the file opens.
Sheets#
Sheet names#
Excel limits sheet names, and the writer applies the same rules so the file always opens:
[ ] : * ? / \are replaced with_, and control characters are removed;- names are cut to 31 characters, and leading or trailing apostrophes are removed;
- an empty name becomes
Sheet1,Sheet2and so on, by position; - duplicates, compared without case, get a suffix:
Orders,Orders (2); Historyis reserved by Excel and becomesHistory (2).
Columns#
columns is a list of column settings by position. Use an empty object for a column that needs nothing.
width is measured in characters of the default font, like the width shown in Excel's column width dialog. A style on a column applies to every cell written in that column.
const sheet: XlsxSheet = {
name: 'Jobs',
columns: [
{ width: 12 },
{ width: 28 },
{},
{ width: 14, style: { numFmt: 'yyyy-mm-dd hh:mm' } },
{ hidden: true },
],
rows: [],
};Rows#
rows holds one entry per spreadsheet row, starting at row 1. An entry is either an array of cells or a row object:
rows: [
['Job', 'Customer', 'Technician', 'Scheduled', 'Internal note'],
['J-58120', 'Harbour View Dental', 'Sofia Rossi', new Date(Date.UTC(2026, 9, 6, 8, 30))],
{ cells: ['J-58121', 'Greenfield Primary School', 'Kwame Mensah'], height: 30 },
{ cells: ['J-58122', 'Atlas Cold Storage', 'Jonas Berg'], style: { fill: '#FFF4E5' } },
]A null or undefined entry leaves a blank row. Row height is in points, up to 409. A row style applies to every cell in that row. Outline properties are covered in Freeze panes, outlines and merges.
Cells#
A cell is either a bare value or an object with a value and a style:
type XlsxPrimitive = string | number | boolean | Date | null | undefined;
type XlsxCellInput = XlsxCell | XlsxPrimitive;| Value | Written as |
|---|---|
string |
Text. Repeated strings are stored once in the shared string table, which keeps files with many repeated labels small. |
number |
A number. NaN and Infinity are left empty. |
boolean |
TRUE or FALSE. |
Date |
A date serial with the yyyy-mm-dd format, unless a style sets another numFmt. Invalid dates are left empty. |
null, undefined |
Nothing. With a style, an empty styled cell. |
{ formula, value? } |
A formula, with an optional cached result. |
Text longer than 32,767 characters, the Excel cell limit, is shortened with a warning.
Formulas#
rows: [
['Product', 'Units', 'Unit price', 'Line total'],
['Edge Router X2', 40, 460, { formula: 'B2*C2', value: 18400 }],
['Sensor Hub', 30, 399, { formula: 'B3*C3', value: 11970 }],
['Total', { formula: 'SUM(B2:B3)', value: 70 }, null, { value: { formula: 'SUM(D2:D3)', value: 30370 }, style: { bold: true } }],
]Write formulas in Excel's English syntax, with or without the leading =. The engine does not calculate formulas itself. It marks the workbook for a full calculation on load, so Excel recalculates every formula when the file is opened. Supply value so that applications and file previews that show cached results display the right number. A formula's cached value can be a string, number, boolean or date.
Plain strings are always stored as text, even if they start with =, so user input cannot turn into a formula.
A complete example#
import { writeXlsx, type XlsxSheet, type XlsxWorkbook } from '@birchui/excel';
interface Visit {
job: string;
customer: string;
technician: string;
start: Date;
hours: number;
billable: boolean;
}
export async function timesheetWorkbook(visits: Visit[]): Promise<Uint8Array> {
const header = { bold: true, fill: '#E8EEF7', border: { bottom: { style: 'thin' as const, color: '#9AA7B8' } } };
const sheet: XlsxSheet = {
name: 'Timesheet',
columns: [
{ width: 10 },
{ width: 30 },
{ width: 18 },
{ width: 18, style: { numFmt: 'dd mmm yyyy hh:mm' } },
{ width: 8, style: { numFmt: '0.00' } },
{ width: 9, style: { align: 'center' } },
],
freeze: { rows: 1 },
autoFilter: true,
rows: [
['Job', 'Customer', 'Technician', 'Start', 'Hours', 'Billable'].map((value) => ({ value, style: header })),
...visits.map((visit) => [visit.job, visit.customer, visit.technician, visit.start, visit.hours, visit.billable]),
[
{ value: 'Total hours', style: { bold: true } },
null,
null,
null,
{ value: { formula: `SUM(E2:E${visits.length + 1})`, value: visits.reduce((sum, v) => sum + v.hours, 0) }, style: { bold: true } },
],
],
};
const workbook: XlsxWorkbook = { title: 'Technician timesheet', creator: 'Fleetwise Operations', sheets: [sheet] };
return writeXlsx(workbook);
}Limits#
| Limit | Behaviour |
|---|---|
| 1,048,576 rows or 16,384 columns per sheet | Throws a RangeError, because Excel cannot open such a file. |
| 32,767 characters per cell | Text is shortened, with a warning. |
| 255 characters column width, 409 points row height | Values are clamped. |
| 7 outline levels | Levels are clamped. |
| 4 GiB per file | Throws a RangeError. |
The writer streams each sheet into chunks as it goes, so memory use grows with the size of the output, not with a copy of your data.