# Writing workbooks

> 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](https://docs.birchui.com/excel/overview.md#license-key). |

```ts
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

**`XlsxWorkbook`** (interface from `@birchui/excel`, full reference: https://docs.birchui.com/api/excel.md)

```ts
interface XlsxWorkbook
```

| Property | Type | Description |
| --- | --- | --- |
| `sheets` | `XlsxSheet[]` |  |
| `creator?` | `string` |  |
| `created?` | `Date` |  |
| `title?` | `string` |  |

```ts
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

**`XlsxSheet`** (interface from `@birchui/excel`, full reference: https://docs.birchui.com/api/excel.md)

```ts
interface XlsxSheet
```

| Property | Type | Description |
| --- | --- | --- |
| `name` | `string` |  |
| `columns?` | `XlsxColumn[]` |  |
| `rows` | `(XlsxRow \| XlsxCellInput[])[]` |  |
| `freeze?` | `{ rows?: number; columns?: number }` |  |
| `autoFilter?` | `boolean \| string` |  |
| `merges?` | `string[]` |  |
| `outlineSummaryBelow?` | `boolean` |  |
| `rightToLeft?` | `boolean` |  |
| `tabColor?` | `string` |  |

### 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`, `Sheet2` and so on, by position;
- duplicates, compared without case, get a suffix: `Orders`, `Orders (2)`;
- `History` is reserved by Excel and becomes `History (2)`.

### Columns

`columns` is a list of column settings by position. Use an empty object for a column that needs nothing.

**`XlsxColumn`** (interface from `@birchui/excel`, full reference: https://docs.birchui.com/api/excel.md)

```ts
interface XlsxColumn
```

| Property | Type | Description |
| --- | --- | --- |
| `width?` | `number` |  |
| `hidden?` | `boolean` |  |
| `outlineLevel?` | `number` |  |
| `style?` | `XlsxCellStyle` |  |

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

```ts
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:

**`XlsxRow`** (interface from `@birchui/excel`, full reference: https://docs.birchui.com/api/excel.md)

```ts
interface XlsxRow
```

| Property | Type | Description |
| --- | --- | --- |
| `cells` | `XlsxCellInput[]` |  |
| `outlineLevel?` | `number` |  |
| `collapsed?` | `boolean` |  |
| `hidden?` | `boolean` |  |
| `height?` | `number` |  |
| `style?` | `XlsxCellStyle` |  |

```ts
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](https://docs.birchui.com/excel/layout.md#outlines).

## Cells

A cell is either a bare value or an object with a value and a style:

```ts
type XlsxPrimitive = string | number | boolean | Date | null | undefined;
type XlsxCellInput = XlsxCell | XlsxPrimitive;
```

**`XlsxCell`** (interface from `@birchui/excel`, full reference: https://docs.birchui.com/api/excel.md)

```ts
interface XlsxCell
```

| Property | Type | Description |
| --- | --- | --- |
| `value` | `XlsxPrimitive \| XlsxFormula` |  |
| `style?` | `XlsxCellStyle` |  |

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

> **Dates are written in UTC**
>
> A `Date` is a point in time, and the engine converts it to a spreadsheet date using its UTC date and time. `new Date(Date.UTC(2026, 9, 6))` is written as 6 October 2026 everywhere. `new Date(2026, 9, 6)`, local midnight, is written as 5 October 2026 at 22:00 for a user in Central European Summer Time. Build calendar dates with `Date.UTC()` or from ISO strings such as `new Date('2026-10-06')`. To keep a local wall-clock time, convert it first:
>
> ```ts
> const asWallClock = (local: Date) =>
>   new Date(Date.UTC(local.getFullYear(), local.getMonth(), local.getDate(), local.getHours(), local.getMinutes()));
> ```

Text longer than 32,767 characters, the Excel cell limit, is shortened with a warning.

### Formulas

```ts
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

```ts title="technician-timesheet.ts"
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.
