# Utilities

> Helpers for A1 cell references, Excel date serials and zip archives that ship with the Excel Engine.

The Excel Engine exports the small building blocks it uses internally. They are handy for building formulas and merge ranges, converting dates you receive as serial numbers, and packaging files.

## Cell references

Spreadsheets address cells as a column letter and a 1-based row number, such as `C7`. The helpers convert between that notation and 0-based indices, the way rows and cells are indexed in arrays.

| Function | Example | Result |
| --- | --- | --- |
| `columnLetter(index)` | `columnLetter(0)`, `columnLetter(27)`, `columnLetter(16383)` | `'A'`, `'AB'`, `'XFD'` |
| `cellRef(rowIndex, colIndex)` | `cellRef(6, 2)` | `'C7'` |
| `parseCellRef(ref)` | `parseCellRef('C7')`, `parseCellRef('$AB$12')` | `{ row: 6, col: 2 }`, `{ row: 11, col: 27 }` |

`parseCellRef` accepts upper- or lower-case letters and absolute references with `$`. It throws an `Error` for anything that is not a single cell reference, and `columnLetter` and `cellRef` throw a `RangeError` for negative or fractional indices.

### Build formulas and ranges

```ts
import { cellRef, columnLetter, type XlsxSheet } from '@birchui/excel';

const months = ['Jul', 'Aug', 'Sep'];
const regions = [
  { name: 'EMEA', revenue: [412000, 398500, 474000] },
  { name: 'North America', revenue: [601200, 655940, 674900] },
  { name: 'APAC', revenue: [270100, 281600, 294510] },
];

const firstDataRow = 1;
const lastDataRow = regions.length;
const totalColumn = months.length + 1;

const sheet: XlsxSheet = {
  name: 'Q3',
  rows: [
    ['Region', ...months, 'Q3 total'],
    ...regions.map((region, i) => [
      region.name,
      ...region.revenue,
      { formula: `SUM(${cellRef(firstDataRow + i, 1)}:${cellRef(firstDataRow + i, months.length)})` },
    ]),
    [
      'Total',
      ...months.map((_, m) => ({ formula: `SUM(${columnLetter(m + 1)}${firstDataRow + 1}:${columnLetter(m + 1)}${lastDataRow + 1})` })),
      { formula: `SUM(${cellRef(firstDataRow, totalColumn)}:${cellRef(lastDataRow, totalColumn)})` },
    ],
  ],
};
```

Remember that `cellRef` takes 0-based indices while the formula text is 1-based: `cellRef(1, 1)` is `B2`.

## Dates

Excel stores a date as the number of days since 30 December 1899, with the time as a fraction of a day: noon on 6 October 2026 is `46301.5`. The engine converts `Date` values for you when writing and reading, and exposes the conversion for data that arrives as serials, for example from an API that exported a spreadsheet.

| Function | Example | Result |
| --- | --- | --- |
| `dateToSerial(date)` | `dateToSerial(new Date('2026-10-06T12:00:00Z'))` | `46301.5` |
| `serialToDate(serial)` | `serialToDate(46301)` | `2026-10-06T00:00:00.000Z` |

Both work in UTC, matching how the writer and reader treat dates; see [Dates are written in UTC](https://docs.birchui.com/excel/writing.md#cells). Results are exact to the millisecond.

Excel counts 29 February 1900 as a real day, a bug kept from Lotus 1-2-3 for compatibility. The helpers reproduce it, so serials before 1 March 1900 line up with what Excel shows. The 1904 date system used by some older Mac workbooks is handled by `readXlsx()` automatically; for raw serials from such a file, add 1,462 days before calling `serialToDate()`.

```ts
import { serialToDate } from '@birchui/excel';

const shippedOn = apiRows.map((row) => ({ ...row, shippedOn: serialToDate(row.shippedSerial) }));
```

## Zip archives

An `.xlsx` file is a zip archive of XML parts, and the engine's zip implementation is exported for other uses, such as bundling several exports into one download.

| Function | Returns | Notes |
| --- | --- | --- |
| `zip(files, { compress? })` | `Promise<Uint8Array>` | DEFLATE-compressed by default through `CompressionStream`; stored uncompressed when `compress` is `false` or the API is missing. |
| `zipSync(files)` | `Uint8Array` | Always uncompressed. |
| `unzip(data, { limits? })` | `Promise<Map<string, Uint8Array>>` | Reads stored and DEFLATE entries, checks every entry's CRC-32 and supports Zip64 archives. Directory entries are skipped. Archives that expand beyond `limits` are rejected. |

Each input file is a `ZipInputFile`:

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

```ts
interface ZipInputFile
```

| Property | Type | Description |
| --- | --- | --- |
| `name` | `string` |  |
| `data` | `Uint8Array` |  |

```ts title="month-end-pack.ts"
import { writeXlsx, zip } from '@birchui/excel';

const encoder = new TextEncoder();

const archive = await zip([
  { name: 'orders-2026-10.xlsx', data: await writeXlsx(ordersWorkbook) },
  { name: 'returns-2026-10.xlsx', data: await writeXlsx(returnsWorkbook) },
  { name: 'README.txt', data: encoder.encode('Month-end export for October 2026, generated by the order desk.\n') },
]);
```

Use forward slashes for folders inside the archive, such as `'reports/orders.xlsx'`. Files are written in the order given.

```ts
import { unzip } from '@birchui/excel';

const entries = await unzip(new Uint8Array(await upload.arrayBuffer()));
for (const [name, bytes] of entries) console.log(name, bytes.byteLength);
```

`unzip` takes a `Uint8Array`; convert a `Blob` or `ArrayBuffer` first, as above. It rejects encrypted entries and archives that fail the integrity check, and reading DEFLATE entries needs `DecompressionStream`.

`unzip` applies the same [size limits](https://docs.birchui.com/excel/reading.md#size-limits) as `readXlsx`, and rejects with a `ZipLimitError` when an archive expands beyond them. Pass `limits` to change any of them:

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

```ts
interface ZipLimits
```

| Property | Type | Description |
| --- | --- | --- |
| `maxEntries` | `number` |  |
| `maxEntryBytes` | `number` |  |
| `maxTotalBytes` | `number` |  |
| `maxRatio` | `number` |  |

```ts
import { ZipLimitError, unzip } from '@birchui/excel';

const MIB = 1024 * 1024;
const bytes = new Uint8Array(await upload.arrayBuffer());

try {
  const entries = await unzip(bytes, { limits: { maxEntries: 500, maxTotalBytes: 64 * MIB } });
  for (const [name, content] of entries) console.log(name, content.byteLength);
} catch (error) {
  if (!(error instanceof ZipLimitError)) throw error;
  console.error(`Rejected ${upload.name}: ${error.code}`);
}
```

## API reference

The full signatures of every function and type are in the [`@birchui/excel` API reference](https://docs.birchui.com/api/excel.md).
