# Sheets and the workbook JSON

> Work with multiple sheets from the tab bar and the API, and load and save workbooks as plain JSON with WorkbookJSON, SheetJSON and CellJSON.

A workbook holds one or more sheets. Users manage them from the tab bar below the grid; your code manages them with the API, and saves and loads the whole workbook as a plain JSON object.

## The tab bar

- **+** adds a sheet at the end.
- Double-click a tab to rename it.
- The tab menu, opened by right-clicking a tab or with `Shift` + `F10` on a focused tab, has **Rename**, **Delete**, **Duplicate**, **Tab color…**, **Hide**, **Unhide** for each hidden sheet, **Move left** and **Move right**.
- A sheet with a `tabColor` shows that colour as the underline of its tab.
- With a tab focused, the arrow keys, `Home` and `End` switch sheets, `F2` renames and `Delete` deletes.
- `Ctrl` + `Page Up` and `Ctrl` + `Page Down` switch to the previous and next visible sheet.

A workbook always keeps at least one visible sheet, so **Delete** and **Hide** are disabled on the last one. Set `sheetTabs: false` to hide the tab bar, for single-sheet tools.

## Sheets in code

```ts
sheet.addSheet('Assumptions', 0);
sheet.renameSheet('Assumptions', 'Rates and terms');
sheet.moveSheet('Rates and terms', 2);
sheet.setSheetHidden('Rates and terms', true);
sheet.setActiveSheet('Loan');
sheet.removeSheet('Scratch');

console.log(sheet.getSheetNames(), sheet.getActiveSheet());
```

| Method | Purpose |
| --- | --- |
| `getSheetNames()` | All sheet names in tab order, including hidden ones. |
| `getActiveSheet()` | The name of the sheet on screen. |
| `addSheet(name?, index?)` | Adds a sheet and returns its name. Without a name it is called `Sheet2`, `Sheet3` and so on. |
| `renameSheet(name, newName)` | Renames a sheet and rewrites every formula that refers to it. |
| `moveSheet(name, index)` | Moves a sheet to a position in the tab order. |
| `setSheetHidden(name, hidden)` | Hides or shows a sheet. Hidden sheets still calculate, and formulas can refer to them. |
| `setActiveSheet(name)` | Shows a sheet. |
| `removeSheet(name)` | Deletes a sheet. Formulas that referred to it show `#REF!`. |
| `duplicateSheet(name, newName?)` | Copies a sheet, puts the copy right after it and returns the new name. Without a name the copy is called `Name (2)`. |
| `setTabColor(name, color)` | Sets the tab colour to a hex colour, or removes it with `null`. |
| `getSheetView(sheet?)`, `setSheetView(view, sheet?)` | Read and change the [sheet view](#sheet-views). |

Sheet names are up to 31 characters, cannot contain `\ / ? * [ ] :`, cannot start or end with an apostrophe, and must be unique. `addSheet()` and `renameSheet()` throw an error for a name that breaks these rules.

Cell methods such as `getValue()` and `setRange()` work on any sheet when the address has a sheet prefix: `sheet.setValue("'Rates and terms'!B2", 0.059)`. Structure methods, such as `insertRows()`, `setFreeze()` and `setColumnWidth()`, apply to the active sheet.

Every change fires `sheetChange` with the sheet name, an `action` of `activate`, `add`, `remove`, `rename`, `move`, `hide` or `show`, and for renames the `previous` name. Sheet operations are undoable.

### Duplicating a sheet

The copy has the cells, formatting, sizes, view and objects of the original. Tables and pivot tables in the copy get a `_2` suffix because their names must be unique, and structured references inside the copy point to the renamed tables. Charts, pictures, shapes and slicers get new ids. Parts of an imported Excel file that are kept only for export (`preserved`) stay with the original and are not copied. Duplicating is one undo step and fires `sheetChange` with the action `add`.

### Hidden and very hidden sheets

A hidden sheet (`hidden: true`) is offered under **Unhide** in the tab menu. A very hidden sheet (`hidden: true, veryHidden: true`), as set from VBA in Excel, is never offered there. `setSheetHidden(name, false)` shows either kind and clears `veryHidden`.

## Sheet views

`SheetJSON.view` holds how a sheet is shown. It is applied when the workbook loads and written back by `toJSON()` and `exportXlsx()`.

| Property | Behaviour |
| --- | --- |
| `zoom` | Zoom of this sheet in percent. A sheet without its own zoom uses the `zoom` option or the last zoom that was set. `setZoom()` and the zoom controls write the zoom of the active sheet, and `zoomChange` also fires when a sheet with a different zoom is activated. |
| `gridlines`, `headings` | Show or hide gridlines and the row and column headings for this sheet. They override the `gridlines` and `headings` options. The View tab toggles write them, and `update({ gridlines })` or `update({ headings })` removes the override of the active sheet. |
| `rightToLeft` | Lays the sheet out from the right. While such a sheet is active the whole component, ribbon included, is mirrored. Numbers stay right-aligned. |
| `showZeros` | `false` shows cells with the value 0 as empty, on screen and in print. **View > Zero values** toggles it. |
| `activeCell`, `selection` | Restored the first time the sheet is activated. `toJSON()` writes the current ones once the selection has moved, or when the loaded view already had them. `selection` is a space-separated list of ranges. |
| `topLeftCell` | The scroll position, restored the first time the sheet is activated. |
| `split` | A split window from Excel. See below. |
| `showFormulas`, `mode` | Kept and exported, not applied. |

```ts
sheet.setSheetView({ zoom: 125, gridlines: false, showZeros: false });
sheet.setSheetView({ gridlines: undefined }); // back to the option
sheet.getSheetView('Loan'); // { zoom: 125, showZeros: false }
```

A key set to `undefined` is removed from the view.

### Split panes

A split divides the grid into two or four panes that show the same sheet and scroll on their own. With a horizontal bar the top and bottom panes share the horizontal position and each has its own vertical position; a vertical bar does the same for left and right.

```ts
sheet.splitPanes('D12'); // bars above row 12 and left of column D
sheet.splitPanes(); // at the active cell
sheet.removeSplit();
```

- **View > Split** toggles a split at the active cell. A cell in the first visible row or column gives one bar, and the first visible cell splits the grid through the middle.
- Drag a bar to move it. Drag it to the edge of the grid, or double-click it, to remove it. `Escape` cancels a drag.
- A bar is a focusable separator: the arrow keys move it by one row or column, and `Delete`, `Backspace` or `Home` removes it.
- `F6` and `Shift` + `F6` move the active cell from pane to pane before going on to the other regions of the component. Clicking a pane makes it the active one.
- Freeze panes and a split exclude each other on a sheet: setting one clears the other. Setting, moving and removing a split are undo steps.
- The split is stored in `view.split` (`x` and `y` in twentieths of a point, `topLeftCell` of the bottom-right pane and `activePane`), as in xlsx files, and is written back.

Selection, editing, merged cells and conditional formats work in every pane. Pictures, charts, shapes, slicers, note and comment markers, table and filter buttons and auditing arrows are drawn in the bottom-right pane only. The top and left panes scroll with the wheel, a trackpad and the keyboard; they have no scrollbars and do not scroll by touch dragging. The scroll positions of the panes are not saved.

**Workbook view.** `WorkbookJSON.activeSheet` is the sheet shown first, when it is visible. `WorkbookJSON.view.showSheetTabs: false` hides the tab bar, like the `sheetTabs` option.

## Named sheet views

A named view is a second way of looking at one sheet: its own filter, its own hidden rows and its own sort indicator. It lets one person filter a shared sheet without changing what the others see. **View > Sheet view** lists **Default view** and the named views of the active sheet, with **Save view…** and, inside a view, **Delete view**.

| Action | What happens |
| --- | --- |
| Save view… | Stores the filter, hidden rows and sort indicator that are on screen under a name, and makes that view the active one. Saving under an existing name replaces it. One undo step. |
| Choose a named view | The default view is put aside and the view's filter and hidden rows are shown. |
| Filter or hide rows inside a view | Changes this view only. The default view, and everyone else's rows, stay as they were. |
| Choose Default view | Your changes are stored in the view you leave, and the default view comes back as it is now, including what others changed in it meanwhile. |

```ts
sheet.saveSheetView('Laptops'); // returns the stored name, or undefined when read-only
sheet.setColumnFilter('B', { kind: 'values', values: ['Laptops'] });
sheet.getSheetViews(); // [{ name: 'Laptops', active: true }]
sheet.applySheetView(null); // back to the default view
sheet.applySheetView('Laptops');
sheet.deleteSheetView('Laptops');
```

`toJSON()` writes the views to `SheetJSON.views` and always writes the default view to `hiddenRows` and `autoFilter`, whichever view is on screen, so a saved workbook opens in its default view. Which view you are in is not saved.

With [collaboration](https://docs.birchui.com/spreadsheet/collaboration.md), the list of views is shared and the view each person is in is not. A filter made inside a view sends nothing; the stored view is sent to the others when you save it or leave it.

Limits:

- A view does not reorder rows. Sorting inside a view sorts the cells, for everyone, as it does outside a view; the view remembers which column carries the sort arrow.
- Hidden columns, the filters of tables, zoom and frozen panes are not part of a view.
- Views are kept in the workbook JSON. They are not written to xlsx, and the sheet views Excel for the web stores in a file are not read.
- Rows inserted or deleted while a view is not on screen do not move the row numbers stored in it.

## Cross-sheet formulas

Refer to another sheet with its name and an exclamation mark: `=SUM(Sales!D2:D500)`, or with quotes when the name contains spaces: `='Rates and terms'!B2`. Hidden sheets are a good place for lookup tables and assumptions that users should not edit directly. See [References](https://docs.birchui.com/spreadsheet/formulas.md#references).

## The workbook JSON

`toJSON()` returns the whole workbook as a JSON-serializable `WorkbookJSON`; `fromJSON(json)`, the `data` option and `update({ data })` load one. Store it in your database, send it to the [headless engine](https://docs.birchui.com/spreadsheet/headless-engine.md) on a server, or convert it to an [xlsx file](https://docs.birchui.com/spreadsheet/xlsx.md).

```ts
const json = sheet.toJSON();
await fetch('/api/models/loan-2026', { method: 'PUT', body: JSON.stringify(json) });

const saved = (await (await fetch('/api/models/loan-2026')).json()) as WorkbookJSON;
sheet.fromJSON(saved);
```

Loading a workbook replaces the current one and clears the undo history.

### WorkbookJSON

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

```ts
interface WorkbookJSON
```

| Property | Type | Description |
| --- | --- | --- |
| `version` | `1` |  |
| `activeSheet?` | `string` |  |
| `sheets` | `SheetJSON[]` |  |
| `names?` | `{ name: string; formula: string; sheet?: string }[]` |  |
| `settings?` | `{ iterative?: boolean; maxIterations?: number; maxChange?: number }` |  |
| `protection?` | `WorkbookProtection` |  |
| `cellStyles?` | `CellStyleDefinition[]` |  |
| `defaultFont?` | `{ family?: string; size?: number }` |  |
| `properties?` | `DocumentProperties` |  |
| `calculation?` | `CalculationSettings` |  |
| `view?` | `WorkbookView` |  |
| `preserved?` | `PreservedWorkbook` |  |

`version` is always `1`. `activeSheet` names the sheet to show first. `names` holds [defined names](https://docs.birchui.com/spreadsheet/formulas.md#defined-names), optionally scoped to a sheet. `settings` stores iterative calculation, which the `iterativeCalculation` option overrides.

### SheetJSON

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

```ts
interface SheetJSON
```

| Property | Type | Description |
| --- | --- | --- |
| `name` | `string` |  |
| `hidden?` | `boolean` |  |
| `tabColor?` | `string` |  |
| `cells` | `Record<string, CellJSON>` |  |
| `columnWidths?` | `Record<string, number>` |  |
| `rowHeights?` | `Record<string, number>` |  |
| `defaultColumnWidth?` | `number` |  |
| `defaultRowHeight?` | `number` |  |
| `drawingOrder?` | `string[]` |  |
| `hiddenRows?` | `number[]` |  |
| `hiddenColumns?` | `number[]` |  |
| `merges?` | `string[]` |  |
| `freeze?` | `{ rows: number; columns: number }` |  |
| `conditionalFormats?` | `ConditionalFormat[]` |  |
| `validations?` | `DataValidation[]` |  |
| `ignoredErrors?` | `IgnoredError[]` |  |
| `views?` | `NamedSheetView[]` |  |
| `autoFilter?` | `AutoFilterState` |  |
| `notes?` | `Record<string, CellNote>` |  |
| `comments?` | `Record<string, CommentThread>` |  |
| `hyperlinks?` | `Record<string, Hyperlink>` |  |
| `protection?` | `SheetProtection` |  |
| `tables?` | `TableJSON[]` |  |
| `outline?` | `OutlineState` |  |
| `images?` | `ImageJSON[]` |  |
| `charts?` | `ChartJSON[]` |  |
| `sparklines?` | `SparklineGroup[]` |  |
| `pageSetup?` | `PageSetup` |  |
| `pivotTables?` | `PivotTableJSON[]` |  |
| `dataTables?` | `DataTableJSON[]` |  |
| `slicers?` | `SlicerJSON[]` |  |
| `shapes?` | `ShapeJSON[]` |  |
| `embeddedObjects?` | `EmbeddedObjectJSON[]` |  |
| `cellImages?` | `Record<string, CellImage>` |  |
| `veryHidden?` | `boolean` |  |
| `view?` | `SheetView` |  |
| `sortState?` | `SortState` |  |
| `preserved?` | `PreservedSheet` |  |

| Property | Content |
| --- | --- |
| `cells` | Cells keyed by A1 address, such as `{ B4: { formula: '=PMT(...)', value: 1539.29 } }`. Only non-empty cells are listed. |
| `columnWidths`, `rowHeights` | Pixel sizes keyed by column letter and by 1-based row number, only for columns and rows that differ from the default. Every exporter and importer, including xlsx, ods and `toJSON()`, uses these keys. On input a `columnWidths` key made of digits is also accepted and read as a 0-based column index. |
| `hiddenRows`, `hiddenColumns` | 1-based row and column numbers. |
| `merges` | Merged ranges, such as `['A1:E1']`. |
| `freeze` | `{ rows, columns }` frozen at the top and left. |
| `conditionalFormats`, `validations` | [Conditional formats](https://docs.birchui.com/spreadsheet/formatting.md#conditional-formatting) and [validation rules](https://docs.birchui.com/spreadsheet/data-tools.md#data-validation). |
| `autoFilter` | The [autofilter](https://docs.birchui.com/spreadsheet/data-tools.md#autofilter) range, the values shown per column and, for conditions that are not value lists, the [criteria](https://docs.birchui.com/spreadsheet/xlsx.md#filters) per column. |
| `comments` | [Threaded comments](https://docs.birchui.com/spreadsheet/xlsx.md#threaded-comments) by cell address, each with its replies. |
| `hidden`, `veryHidden`, `tabColor` | Whether the sheet is hidden or [very hidden](#hidden-and-very-hidden-sheets), and its tab colour. |
| `view` | The [sheet view](#sheet-views): zoom, gridlines, headings, direction, selection and split. |
| `sortState` | The last sort of the autofilter range, shown as an arrow on the filter button. Tables carry their own `sortState`. |

### CellJSON

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

```ts
interface CellJSON
```

| Property | Type | Description |
| --- | --- | --- |
| `value?` | `CellValue \| { error: ErrorCode }` |  |
| `formula?` | `string` |  |
| `style?` | `CellStyle` |  |
| `richText?` | `RichTextRun[]` |  |
| `spill?` | `string` |  |
| `spillValues?` | `(CellValue \| { error: ErrorCode })[][]` |  |

A cell has a `value`, a `formula`, a `style`, or a combination:

```json
{
  "A1": { "value": "Principal" },
  "B1": { "value": 250000, "style": { "numberFormat": "#,##0.00" } },
  "B4": { "formula": "=PMT(B2/12, B3*12, -B1)", "value": 1539.293001065986 },
  "C9": { "formula": "=1/0", "value": { "error": "#DIV/0!" } }
}
```

- Values are numbers, strings, booleans or errors written as `{ "error": "#N/A" }`. Dates and times are serial numbers with a date format; use `dateToSerial()` to produce them.
- For formula cells, `value` is the cached result from the last calculation. When loading, formulas are recalculated, so the cached value only matters to tools that read the JSON without the engine.
- A dynamic array formula is stored on its anchor cell only; its spilled results are recalculated after loading.

## Defined names and the Name Manager

`defineName(name, formula, sheet?)` adds a workbook-level name, or a sheet-level name when you pass a sheet. `getNames()` lists the names and `removeName(name, sheet?)` deletes one. Names can be used anywhere a reference can, including `SUM(FirstQuarter)` and the name box.

```ts
sheet.defineName('TaxRate', '=Settings!$B$2');
sheet.getNames(); // [{ name: 'TaxRate', formula: '=Settings!$B$2' }]
```

`Ctrl` + `F3` or `openDialog('nameManager')` opens the Name Manager. It lists every name with what it refers to and its scope, and lets users add, edit and delete names. It rejects names that look like cell references, contain spaces or repeat a name in the same scope. Every change can be undone.

## Watching for changes

To keep a server copy in sync, save after changes settle:

```ts
let pending: ReturnType<typeof setTimeout> | undefined;

const save = () => {
  clearTimeout(pending);
  pending = setTimeout(() => saveModel(sheet.toJSON()), 1500);
};

sheet.on('cellChange', save);
sheet.on('sheetChange', save);
```

`cellChange` fires for every changed cell, with the old and new value, the formula and a `source`: `edit`, `api`, `paste`, `fill`, `undo`, `redo`, `replace`, `clear` or `sort`. Cells that change only because a formula recalculated do not fire `cellChange`; the `recalculated` event reports those.
