# Spreadsheet overview

> An embeddable, Excel-compatible spreadsheet for web apps, with a formula engine of 501 functions, dynamic arrays, incremental recalculation and xlsx import and export.

Birch UI Spreadsheet puts a real spreadsheet inside your app: the grid, formula bar and sheet tabs people know from Excel, backed by an Excel-compatible formula engine. It is for products where users model, plan and calculate: pricing calculators, budgets, quoting tools, financial models, data-entry screens that need formulas.

- **Formula engine** with 501 functions plus `LET` and `LAMBDA`, dynamic arrays that spill, cross-sheet references, defined names and incremental recalculation. See [Formulas](https://docs.birchui.com/spreadsheet/formulas.md) and the [function reference](https://docs.birchui.com/spreadsheet/functions.md).
- **Component** with multiple sheets, frozen panes, merged cells, number formats, conditional formatting, data validation, autofilter, sort, find and replace, the fill handle, clipboard and undo.
- **xlsx import and export** of values, formulas, styles, layout, tables, charts, pivot tables, slicers and shapes, with an import report, progress and cancelling. See [Excel files](https://docs.birchui.com/spreadsheet/xlsx.md).
- **Other files**: [password-protected workbooks](https://docs.birchui.com/spreadsheet/encryption.md), and [CSV, TSV and OpenDocument](https://docs.birchui.com/spreadsheet/file-formats.md) files.
- **A headless engine** that runs the same formulas in Node or a worker. See [Headless engine](https://docs.birchui.com/spreadsheet/headless-engine.md).

> **Spreadsheet: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md**
>
> Birch UI Spreadsheet is a one-time purchase of $399 per developer, with free updates forever and unlimited apps and end users. Every feature works without a key while you evaluate; non-local hosts show a small watermark.

**Live demo: Loan amortisation sheet** (runs on the HTML version of this page). Source of `demos/spreadsheet-loan.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createSpreadsheet } from '@birchui/spreadsheet';
import { docsTheme, layout, onDocsThemeChange } from './_shared';

export const meta = { title: 'Loan amortisation sheet', height: 560 };

const money = { numberFormat: '#,##0.00' };
const header = { bold: true, fill: '#1f3a5f', color: '#ffffff' };

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  toolbar.append('Change the principal, rate or term in column B; the payment and all 360 schedule rows recalculate.');
  const sheet = createSpreadsheet(body, {
    theme: docsTheme(),
    height: '100%',
    data: {
      version: 1,
      sheets: [
        {
          name: 'Loan',
          freeze: { rows: 6, columns: 0 },
          columnWidths: { A: 90, B: 130, C: 130, D: 130, E: 150 },
          cells: {
            A1: { value: 'Principal' },
            B1: { value: 250000, style: money },
            A2: { value: 'Annual rate' },
            B2: { value: 0.0625, style: { numberFormat: '0.00%' } },
            A3: { value: 'Years' },
            B3: { value: 30 },
            A4: { value: 'Payment' },
            B4: { formula: '=PMT(B2/12, B3*12, -B1)', style: { ...money, bold: true } },
            D1: { value: 'Total interest' },
            E1: { formula: '=B4*B3*12-B1', style: money },
            A6: { value: 'Month', style: header },
            B6: { value: 'Payment', style: header },
            C6: { value: 'Interest', style: header },
            D6: { value: 'Principal', style: header },
            E6: { value: 'Balance', style: header },
            A7: { formula: '=SEQUENCE(B3*12)' },
          },
        },
      ],
    },
  });
  const rows = 360;
  const schedule = Array.from({ length: rows }, (_, i) => {
    const r = i + 7;
    return [
      `=IF(A${r}="","",$B$4)`,
      `=IF(A${r}="","",IPMT($B$2/12, A${r}, $B$3*12, -$B$1))`,
      `=IF(A${r}="","",B${r}-C${r})`,
      `=IF(A${r}="","",$B$1-SUM($D$7:D${r}))`,
    ];
  });
  sheet.setRange(`B7:E${rows + 6}`, schedule);
  sheet.setStyle(`B7:E${rows + 6}`, money);

  const offs = [
    sheet.on('cellChange', ({ address, newValue, source }) => {
      if (source !== 'edit' && source !== 'paste') return;
      status.textContent = `${address} = ${String(newValue)}. Monthly payment is now ${sheet.getDisplayText('B4')}.`;
    }),
    sheet.on('recalculated', (event) => {
      if ('durationMs' in event && typeof event.durationMs === 'number') {
        status.textContent = `Recalculated in ${event.durationMs.toFixed(1)} ms. Payment ${sheet.getDisplayText('B4')}.`;
      }
    }),
  ];
  status.textContent = `Monthly payment ${sheet.getDisplayText('B4')}, total interest ${sheet.getDisplayText('E1')}.`;
  const stopTheme = onDocsThemeChange((theme) => sheet.update({ theme }));
  return () => {
    for (const off of offs) off();
    stopTheme();
    sheet.destroy();
  };
}
```

## Install

```bash
npm install @birchui/spreadsheet
```

The package depends on `@birchui/core`, `@birchui/license` and `@birchui/excel`, which npm installs with it. Styles are injected when the first spreadsheet is created; to use a stylesheet instead, pass `injectStyles: false` and import `@birchui/spreadsheet/styles.css`.

## Quick start: a loan amortisation schedule

The sheet takes a principal, an annual rate and a term, calculates the monthly payment with `PMT`, and builds a month-by-month schedule with `IPMT` for interest and `PPMT` for principal. `SEQUENCE` numbers the months and spills them down column A.

```ts title="loan-calculator.ts"
import { createSpreadsheet, type WorkbookJSON } from '@birchui/spreadsheet';

const money = { numberFormat: '#,##0.00' };
const header = { bold: true, fill: '#1f3a5f', color: '#ffffff' };

const loan: WorkbookJSON = {
  version: 1,
  sheets: [
    {
      name: 'Loan',
      freeze: { rows: 6, columns: 0 },
      columnWidths: { A: 80, B: 120, C: 120, D: 120, E: 140 },
      cells: {
        A1: { value: 'Principal' },
        B1: { value: 250000, style: money },
        A2: { value: 'Annual rate' },
        B2: { value: 0.0625, style: { numberFormat: '0.00%' } },
        A3: { value: 'Years' },
        B3: { value: 30 },
        A4: { value: 'Payment' },
        B4: { formula: '=PMT(B2/12, B3*12, -B1)', style: { ...money, bold: true } },
        A6: { value: 'Month', style: header },
        B6: { value: 'Payment', style: header },
        C6: { value: 'Interest', style: header },
        D6: { value: 'Principal', style: header },
        E6: { value: 'Balance', style: header },
        A7: { formula: '=SEQUENCE(B3*12)' },
      },
    },
  ],
};

const sheet = createSpreadsheet(document.querySelector<HTMLElement>('#loan')!, {
  data: loan,
  height: 520,
  licenseKey: import.meta.env.VITE_BIRCHUI_LICENSE_KEY,
});

const rows = [['=$B$4', '=IPMT($B$2/12, A7, $B$3*12, -$B$1)', '=PPMT($B$2/12, A7, $B$3*12, -$B$1)', '=$B$1-D7']];
for (let month = 8; month <= 366; month++) {
  rows.push([
    '=$B$4',
    `=IPMT($B$2/12, A${month}, $B$3*12, -$B$1)`,
    `=PPMT($B$2/12, A${month}, $B$3*12, -$B$1)`,
    `=E${month - 1}-D${month}`,
  ]);
}
sheet.setRange('B7', rows);
sheet.setStyle('B7:E366', money);

console.log(sheet.getDisplayText('B4'));
```

The last line prints `1,539.29`, the monthly payment. Change the rate in `B2` and all 360 rows recalculate; only the cells that depend on `B2` are evaluated.

Users can build the same schedule by hand: enter the first two rows, select `B8:E8` and drag the fill handle down to row 366, and the relative references shift as in Excel.

## The widget contract

`createSpreadsheet(container, options)` renders into `container` and returns a `SpreadsheetApi`. Like every Birch UI widget it has `element`, `update(partial)`, `on(event, listener)` and `destroy()`, plus methods for cells, styles, structure, sheets and files:

```ts
sheet.setValue('B2', 0.059);
sheet.getValue('B4');
sheet.getFormula('B4');
sheet.getDisplayText("'Loan'!E366");

sheet.on('cellChange', ({ address, oldValue, newValue, source }) => {
  console.log(`${address}: ${String(oldValue)} -> ${String(newValue)} (${source})`);
});

sheet.update({ readOnly: true, theme: 'dark' });
```

Addresses accept a sheet prefix such as `'Q3 Budget'!B4`, or a [defined name](https://docs.birchui.com/spreadsheet/formulas.md#defined-names). Every method and event is listed in the [API reference](https://docs.birchui.com/spreadsheet/api.md).

## Editing like Excel

- Type to replace a cell, or press `F2` or double-click to edit in place. `Enter` and `Tab` commit and move, `Shift` reverses the direction, `Escape` cancels.
- While editing a formula, arrow keys or clicks insert references (point mode), the references you type are highlighted in the grid, and `F4` cycles `$` markers.
- Function names autocomplete with argument hints.
- The formula bar shows the active cell's formula, and the name box jumps to any address or defined name.
- A [ribbon toolbar](https://docs.birchui.com/spreadsheet/toolbar.md) with File, Home, Insert, Page Layout, Formulas, Data, Review and View tabs puts every command one click or `Alt` + letter away, and `Alt` + `Q` searches them by name. The ribbon is three rows tall, one row tall or collapsed to its tabs (`ribbon: { mode: 'classic' | 'simplified' | 'collapsed' | 'auto' }`). Use `toolbar: 'compact'` for a single row without tabs, or `toolbar: false` to hide it.
- A right-click or `Shift` + `F10` opens a menu with clipboard, paste special, insert and delete, hide and unhide, sort, filter, merge, freeze and find commands.
- Drag the selection border to move cells (`Ctrl` copies), double-click the fill handle to fill down, drag the freeze bars, and zoom from the status bar.

The keyboard shortcuts are listed in [Data tools](https://docs.birchui.com/spreadsheet/data-tools.md#keyboard-shortcuts).

## Use it in your framework

There is no framework-specific spreadsheet package. Pass `spreadsheetDefinition` to your adapter's generic factory, once, and use the result like any component. Options become props, and events become the framework's event syntax.

**React**

```tsx
import { createReactComponent } from '@birchui/react';
import { spreadsheetDefinition, type SpreadsheetApi } from '@birchui/spreadsheet';
import { useRef } from 'react';

const BirchSpreadsheet = createReactComponent(spreadsheetDefinition);

export function LoanCalculator() {
  const sheet = useRef<SpreadsheetApi>(null);
  return (
    <BirchSpreadsheet
      ref={sheet}
      data={loan}
      height={520}
      onCellChange={({ address, newValue }) => console.log(address, newValue)}
    />
  );
}
```

**Vue**

```vue
<script setup lang="ts">
import { createVueComponent } from '@birchui/vue';
import { spreadsheetDefinition } from '@birchui/spreadsheet';

const BirchSpreadsheet = createVueComponent(spreadsheetDefinition);
</script>

<template>
  <BirchSpreadsheet :data="loan" :height="520" @cell-change="({ address, newValue }) => console.log(address, newValue)" />
</template>
```

**Angular**

```ts
import { Component, input, output } from '@angular/core';
import { injectBirchWidget, type WidgetOutputs } from '@birchui/angular';
import { spreadsheetDefinition, type SpreadsheetEvents, type SpreadsheetOptions } from '@birchui/spreadsheet';

@Component({ selector: 'app-spreadsheet', standalone: true, template: '', styles: ':host { display: block; }' })
export class SpreadsheetComponent implements WidgetOutputs<SpreadsheetEvents> {
  readonly options = input<SpreadsheetOptions>({});

  readonly ready = output<SpreadsheetEvents['ready']>();
  readonly cellChange = output<SpreadsheetEvents['cellChange']>();
  readonly selectionChange = output<SpreadsheetEvents['selectionChange']>();
  readonly sheetChange = output<SpreadsheetEvents['sheetChange']>();
  readonly recalculated = output<SpreadsheetEvents['recalculated']>();
  readonly error = output<SpreadsheetEvents['error']>();
  readonly viewportScroll = output<SpreadsheetEvents['viewportScroll']>();

  private readonly widget = injectBirchWidget(spreadsheetDefinition, this, () => this.options());

  get api() {
    return this.widget.instance;
  }
}
```

**Svelte**

```svelte
<script lang="ts">
  import { createSvelteAction } from '@birchui/svelte';
  import { spreadsheetDefinition } from '@birchui/spreadsheet';

  const birchSpreadsheet = createSvelteAction(spreadsheetDefinition);
</script>

<div use:birchSpreadsheet={{ data: loan, height: 520, on: { cellChange: (e) => console.log(e.address) } }}></div>
```

**Solid**

```tsx
import { createSolidComponent } from '@birchui/solid';
import { spreadsheetDefinition } from '@birchui/spreadsheet';

const BirchSpreadsheet = createSolidComponent(spreadsheetDefinition);

export const LoanCalculator = () => <BirchSpreadsheet data={loan} height={520} />;
```

**Web Component**

```html
<birchui-spreadsheet id="loan"></birchui-spreadsheet>

<script type="module">
  import { createElementRegistration } from '@birchui/element';
  import { spreadsheetDefinition } from '@birchui/spreadsheet';

  createElementRegistration(spreadsheetDefinition).define();

  const element = document.querySelector('#loan');
  element.options = { data: loan, height: 520 };
  element.addEventListener('cell-change', (event) => console.log(event.detail.address));
</script>
```

The element's tag name is `birchui-spreadsheet`, and events are dispatched as kebab-case `CustomEvent`s with the payload in `detail`. The framework guides, starting with [React](https://docs.birchui.com/frameworks/react.md), cover refs, server rendering and typing for each adapter.

## Accessibility

The grid uses `role="grid"` with `aria-rowcount` and `aria-colcount` over the full 1,048,576 by 16,384 address space. Each cell has an accessible name with its address, value and formula, such as "B4, 1,539.29, formula =PMT(B2/12, B3*12, -B1)", and a live region announces edits and errors. Everything, including the sheet tabs and menus, works by keyboard.

## Licensing

Birch UI Spreadsheet is a commercial product. Prices are one-time, with free updates forever, including major versions, and unlimited apps and end users:

| Tier | Price | Seats |
| --- | --- | --- |
| Developer | $399 | One named developer |
| Team | $1,499 | Up to 5 developers |
| Company | $3,999 | Unlimited developers in one organization |

Colleagues who only build or deploy the app need no seat. The Birch UI Complete bundle includes the Spreadsheet, and a Spreadsheet key also covers the [Excel Engine](https://docs.birchui.com/excel/overview.md). See [Pricing](https://docs.birchui.com/getting-started/pricing.md).

Pass the key as `licenseKey`, or set it once for the app with `setLicenseKey()` from `@birchui/license`. The key is verified offline, without network calls. Without a valid key every feature keeps working; the spreadsheet shows a small watermark on non-local hosts (not on `localhost`, `127.0.0.1` or `*.local`), and the console shows one warning. `update({ licenseKey })` re-checks a new key immediately.

The [headless engine](https://docs.birchui.com/spreadsheet/headless-engine.md) does not check a license key; the [xlsx functions](https://docs.birchui.com/spreadsheet/xlsx.md) pass your key to the Excel Engine.

## Next steps

- [Formulas](https://docs.birchui.com/spreadsheet/formulas.md) and the [function reference](https://docs.birchui.com/spreadsheet/functions.md)
- The [toolbar and status bar](https://docs.birchui.com/spreadsheet/toolbar.md)
- [Formatting](https://docs.birchui.com/spreadsheet/formatting.md) and [data tools](https://docs.birchui.com/spreadsheet/data-tools.md)
- [Pivot tables](https://docs.birchui.com/spreadsheet/pivot-tables.md) and [slicers](https://docs.birchui.com/spreadsheet/slicers.md)
- [Sheets and the workbook JSON](https://docs.birchui.com/spreadsheet/sheets.md)
- [Tables and structured references](https://docs.birchui.com/spreadsheet/tables.md), [outline grouping](https://docs.birchui.com/spreadsheet/outline.md), [notes and hyperlinks](https://docs.birchui.com/spreadsheet/notes-and-links.md) and [protection](https://docs.birchui.com/spreadsheet/protection.md)
- [Charts](https://docs.birchui.com/spreadsheet/charts.md), [images](https://docs.birchui.com/spreadsheet/images.md), [shapes](https://docs.birchui.com/spreadsheet/shapes.md) and [sparklines](https://docs.birchui.com/spreadsheet/sparklines.md)
- [Printing and page setup](https://docs.birchui.com/spreadsheet/printing.md), [formula auditing](https://docs.birchui.com/spreadsheet/auditing.md) and [keyboard shortcuts](https://docs.birchui.com/spreadsheet/keyboard.md)
- [Excel files](https://docs.birchui.com/spreadsheet/xlsx.md), [password-protected workbooks](https://docs.birchui.com/spreadsheet/encryption.md) and [CSV and OpenDocument files](https://docs.birchui.com/spreadsheet/file-formats.md)
- The [headless engine](https://docs.birchui.com/spreadsheet/headless-engine.md) and [worker calculation](https://docs.birchui.com/spreadsheet/worker-calculation.md)
- [Collaboration](https://docs.birchui.com/spreadsheet/collaboration.md): operations, concurrent edits and presence cursors
- [Performance](https://docs.birchui.com/spreadsheet/performance.md), [API reference](https://docs.birchui.com/spreadsheet/api.md) and [limitations](https://docs.birchui.com/spreadsheet/limitations.md)
