# Reading files

> Read xlsx files into arrays of values or records with readXlsx and sheetToObjects, including dates, booleans, merged ranges and formula results.

`readXlsx()` opens an `.xlsx` file and returns the values of every sheet. It is built for importing data, such as price lists, timesheets or customer lists, rather than for round-tripping formatting.

## Read a file

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

const workbook = await readXlsx(file);

for (const sheet of workbook.sheets) {
  console.log(sheet.name, `${sheet.rows.length} rows`, sheet.merges);
}
```

`readXlsx(data, options?)` accepts:

- a `Blob` or `File`, for example from `<input type="file">`, a drop zone or `fetch().then((r) => r.blob())`;
- an `ArrayBuffer`;
- a `Uint8Array`, including a Node `Buffer`.

The only option is `licenseKey`, for passing your key to this call instead of setting it once with `setLicenseKey()`; see [License key](https://docs.birchui.com/excel/overview.md#license-key).

```ts
const workbook = await readXlsx(file, { licenseKey: import.meta.env.VITE_BIRCHUI_LICENSE_KEY });
```

It resolves to an `XlsxReadResult`:

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

```ts
interface XlsxReadResult
```

| Property | Type | Description |
| --- | --- | --- |
| `sheets` | `XlsxReadSheet[]` |  |

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

```ts
interface XlsxReadSheet
```

| Property | Type | Description |
| --- | --- | --- |
| `name` | `string` |  |
| `rows` | `XlsxPrimitive[][]` |  |
| `merges` | `string[]` |  |

Sheets come in workbook order, with the names users see on the tabs.

## The rows array

`rows` is a dense 2D array: `rows[0]` is spreadsheet row 1 and `rows[0][0]` is cell `A1`. Every row has the same length, the width of the sheet's widest row, and missing cells are `null`. Blank rows inside the data stay in place as rows of `null`, so row indices match the spreadsheet.

```ts
const [sheet] = (await readXlsx(file)).sheets;
const header = sheet.rows[0];
const firstOrderNumber = sheet.rows[1]?.[0];
```

## Value types

| In the spreadsheet | You get |
| --- | --- |
| Text, including rich text with mixed formatting | `string`, with formatting removed |
| A number | `number` |
| A number formatted as a date or time | `Date` |
| `TRUE` / `FALSE` | `boolean` |
| A formula | Its cached result: `string`, `number`, `boolean` or `Date` |
| An error such as `#DIV/0!` or `#N/A` | The error text as a `string` |
| An empty cell | `null` |

Formulas are not evaluated and their text is not returned; you get the result Excel saved with the file. Files written by tools that do not store results show `null` for those cells.

### Dates

Spreadsheets store dates as numbers with a date format. The reader looks at each cell's number format and returns a `Date` when the format shows a date or time, both for Excel's built-in date formats and for custom codes such as `dd/mm/yyyy` or `[h]:mm`. Files that use the 1904 date system, common in older Mac workbooks, are converted correctly.

Dates are returned in UTC: a cell showing `2026-10-06` becomes `2026-10-06T00:00:00.000Z`. To display it as a calendar date in local time, read the UTC parts:

```ts
const asCalendarDate = (value: Date) =>
  new Date(value.getUTCFullYear(), value.getUTCMonth(), value.getUTCDate());
```

Or format it with `timeZone: 'UTC'`:

```ts
new Intl.DateTimeFormat('en-GB', { dateStyle: 'medium', timeZone: 'UTC' }).format(value);
```

Numbers that are not formatted as dates stay numbers. If a column holds date serials with a general format, convert them yourself with [`serialToDate()`](https://docs.birchui.com/excel/utilities.md#dates).

## Records with `sheetToObjects`

Most imports want one object per row, keyed by the header. `sheetToObjects(sheet, options?)` does that:

```ts
import { readXlsx, sheetToObjects } from '@birchui/excel';

interface PriceRow {
  SKU: string;
  Product: string;
  'Unit price': number;
  'Valid from': Date;
}

const { sheets } = await readXlsx(file);
const prices = sheetToObjects(sheets[0]) as unknown as PriceRow[];
```

| Sheet | Result |
| --- | --- |
| Row 1: `SKU`, `Product`, `Unit price`, `Valid from` | Keys |
| Row 2: `ER-X2`, `Edge Router X2`, `460`, `2026-10-01` | `{ SKU: 'ER-X2', Product: 'Edge Router X2', 'Unit price': 460, 'Valid from': Date }` |

The rules:

- The header row is the first row by default. Pass `{ headerRow: 2 }` to use the third row, for files with a title above the table; rows above it are ignored.
- Header text is trimmed. A blank header uses the column letter, such as `F`.
- Duplicate headers get a suffix: `Amount`, `Amount_2`.
- Rows in which every cell is empty are skipped.
- Columns with neither a header nor any data are left out.
- Missing values are `null`.

### Validate and convert

Spreadsheets are typed by hand, so check what you receive before using it:

```ts
interface Customer {
  accountNo: string;
  name: string;
  creditLimit: number;
  since: Date | null;
}

function toCustomers(records: Record<string, unknown>[]): { customers: Customer[]; errors: string[] } {
  const customers: Customer[] = [];
  const errors: string[] = [];
  records.forEach((record, index) => {
    const line = index + 2;
    const accountNo = String(record['Account no.'] ?? '').trim();
    const creditLimit = Number(record['Credit limit']);
    if (!accountNo) errors.push(`Row ${line}: account number is missing`);
    else if (!Number.isFinite(creditLimit)) errors.push(`Row ${line}: credit limit is not a number`);
    else
      customers.push({
        accountNo,
        name: String(record['Customer'] ?? ''),
        creditLimit,
        since: record['Customer since'] instanceof Date ? record['Customer since'] : null,
      });
  });
  return { customers, errors };
}
```

To load the result into a grid with header matching and type conversion done for you, use [Grid Pro's `importExcel()`](https://docs.birchui.com/grid-pro/excel-export.md#import-a-spreadsheet).

## Merged cells

`merges` lists merged ranges in A1 notation, such as `'A1:D1'`. The value of a merged area is in its top-left cell; the other cells are `null`. To fill them, for example to repeat a merged category label down its rows:

```ts
import { parseCellRef, type XlsxReadSheet } from '@birchui/excel';

function fillMerges(sheet: XlsxReadSheet): void {
  for (const range of sheet.merges) {
    const [start, end = start] = range.split(':');
    const from = parseCellRef(start);
    const to = parseCellRef(end);
    const value = sheet.rows[from.row]?.[from.col] ?? null;
    for (let r = from.row; r <= to.row; r++) {
      for (let c = from.col; c <= to.col; c++) {
        if (sheet.rows[r]) sheet.rows[r][c] = value;
      }
    }
  }
}
```

## What is not read

The reader focuses on data. It does not return styles, column widths, comments, images, charts, pivot table definitions, data validation or formula text. Hidden rows and sheets are read like visible ones.

## Size limits

An `.xlsx` file is a zip archive, and a zip archive of a few kilobytes can be built to expand into gigabytes. Reading one without a limit can exhaust the memory of a browser tab or a server process, so `readXlsx()` refuses archives that expand beyond these limits:

| Limit | Default | Applies to |
| --- | --- | --- |
| `maxEntries` | 10,000 | The number of entries in the archive. |
| `maxEntryBytes` | 512 MiB | The expanded size of one entry, such as a sheet. |
| `maxTotalBytes` | 1 GiB | The expanded size of all entries together. |
| `maxRatio` | 200 | How many times one entry may expand. Entries of 1 MiB or less are not checked. |

The reader checks the sizes the archive declares before it expands anything. It then stops expanding an entry as soon as the entry produces more than it declared, so an archive that understates its sizes is rejected after a few kilobytes of work.

Workbooks of real data stay far below the defaults. In our measurements, a workbook of a million cells of order data expands 10 times, and a sheet of three million identical cells expands 16 times, to about 100 MiB. The one legitimate case that can exceed `maxRatio` is a large picture stored without compression, such as a scanned blank page saved as a bitmap.

When you accept uploads from people you do not know, set the limits to what your page or server can afford:

```ts title="import-upload.ts"
import { ZipLimitError, readXlsx } from '@birchui/excel';

const MIB = 1024 * 1024;

try {
  const workbook = await readXlsx(file, { limits: { maxEntryBytes: 64 * MIB, maxTotalBytes: 128 * MIB } });
  renderPreview(workbook);
} catch (error) {
  if (!(error instanceof ZipLimitError)) throw error;
  showError(`"${file.name}" is too large to import.`);
  console.error(error.code, error.entryName, error.actual, error.limit);
}
```

Pass only the limits you want to change; the others keep their defaults. `Infinity` turns one off. A `ZipLimitError` carries the details of the limit that was exceeded:

| Property | Value |
| --- | --- |
| `code` | `'too-many-entries'`, `'entry-too-large'`, `'archive-too-large'` or `'ratio-too-high'`. |
| `limit` | The limit that applied. |
| `actual` | The value found in the file: an entry count, a size in bytes or a ratio. |
| `entryName` | The entry concerned, for `'entry-too-large'` and `'ratio-too-high'`. |

The defaults are exported as `DEFAULT_ZIP_LIMITS`. The limits bound how much memory one file can make the reader use. They do not make a large workbook quick to read: use a [Web Worker](https://docs.birchui.com/excel/workers.md#reading-in-a-worker) for that.

## Errors

`readXlsx()` rejects its promise when the input cannot be read as a workbook:

| Error | Cause |
| --- | --- |
| `ZipLimitError` | A file that expands beyond the [size limits](#size-limits). |
| `Not an xlsx file: the workbook part is missing` | A zip file that is not a workbook, such as a `.docx`. |
| `Invalid zip archive: …` | Not a zip file at all: a legacy `.xls`, a CSV renamed to `.xlsx`, a truncated download, or a password-protected workbook, which Excel stores in a different, encrypted container. |
| `Encrypted zip entries are not supported: …` | A zip file whose entries are encrypted. |
| `DEFLATE entries require DecompressionStream…` | A runtime without `DecompressionStream`. All current browsers and Node 20 or later have it. |

```ts
try {
  const workbook = await readXlsx(file);
  renderPreview(workbook);
} catch (error) {
  showError(`"${file.name}" could not be read as an Excel workbook. Save it as .xlsx and try again.`);
  console.error(error);
}
```

Reading happens in memory. For files of several megabytes, read in a [Web Worker](https://docs.birchui.com/excel/workers.md#reading-in-a-worker) to keep the page responsive.
