# Spreadsheet API

> Options, methods and events of createSpreadsheet, and the other exports of @birchui/spreadsheet.

`createSpreadsheet(container, options)` renders a spreadsheet into `container` and returns a `SpreadsheetApi`. This page lists every option, method and event. The complete generated reference, with every type, is on the [`@birchui/spreadsheet` API page](https://docs.birchui.com/api/spreadsheet.md).

```ts
import { createSpreadsheet } from '@birchui/spreadsheet';

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

## Options

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

```ts
interface SpreadsheetOptions
```

| Property | Type | Description |
| --- | --- | --- |
| `licenseKey?` | `string` |  |
| `data?` | `WorkbookJSON` |  |
| `theme?` | `SpreadsheetTheme` |  |
| `sheetTheme?` | `SheetTheme` |  |
| `height?` | `number \| string` |  |
| `readOnly?` | `boolean` |  |
| `injectStyles?` | `boolean` |  |
| `formulaBar?` | `boolean` |  |
| `autoComplete?` | `boolean` |  |
| `pasteOptionsButton?` | `boolean` |  |
| `errorChecking?` | `boolean` |  |
| `csvImportDialog?` | `boolean` |  |
| `datePicker?` | `boolean` |  |
| `spellcheck?` | `SpellChecker` |  |
| `sheetTabs?` | `boolean` |  |
| `statusBar?` | `boolean` |  |
| `toolbar?` | `ToolbarMode` |  |
| `toolbarOptions?` | `ToolbarOptions` |  |
| `ribbon?` | `RibbonOptions` |  |
| `zoom?` | `number` |  |
| `headings?` | `boolean` |  |
| `userName?` | `string` |  |
| `mentions?` | `MentionOptions` |  |
| `gridlines?` | `boolean` |  |
| `defaultColumnWidth?` | `number` |  |
| `defaultRowHeight?` | `number` |  |
| `dynamicArrays?` | `boolean` |  |
| `iterativeCalculation?` | `boolean \| { maxIterations?: number; maxChange?: number }` |  |
| `now?` | `() => Date` |  |
| `ariaLabel?` | `string` |  |
| `localeText?` | `LocaleTextInput` |  |
| `rtl?` | `boolean` |  |
| `locale?` | `string \| FormatLocale` |  |
| `localizedFormulas?` | `boolean` |  |
| `customLists?` | `string[][]` |  |
| `calculation?` | `CalculationMode` |  |
| `calculationWorker?` | `() => WorkerLike` |  |
| `resolveImage?` | `(request: ImageResolveRequest) => string \| undefined` |  |
| `functions?` | `CustomFunctionSet` |  |
| `validation?` | `ValidationMode` |  |
| `enforceProtection?` | `boolean` |  |
| `fileDrop?` | `boolean` |  |

| Option | Default | Effect |
| --- | --- | --- |
| `data` | one empty sheet | The workbook to load, as [`WorkbookJSON`](https://docs.birchui.com/spreadsheet/sheets.md#workbookjson). |
| `licenseKey` | the key from `setLicenseKey()` | Your Spreadsheet or Complete license key. |
| `height` | the container's height | A number of pixels or a CSS length, such as `'70vh'`. |
| `theme` | inherited from the page | `'light'`, `'dark'` or `'auto'`, which follows the operating system. |
| `sheetTheme` | `'light'` | What the cells do in a dark theme. `'light'` keeps the sheet area white, as Excel does, and only the toolbar, formula bar, headers, tabs, menus and dialogs go dark. `'match'` makes the cells dark too. See [Themes](https://docs.birchui.com/spreadsheet/accessibility.md#themes). |
| `readOnly` | `false` | Users can select, copy and search but not edit. |
| `toolbar` | `'ribbon'` | The [toolbar](https://docs.birchui.com/spreadsheet/toolbar.md): `'ribbon'`, `'compact'` or `false`. |
| `toolbarOptions` | none | Hide tabs and commands, add custom buttons, turn `Alt` key tips off. |
| `ribbon` | `{ mode: 'classic' }` | [Ribbon layout](https://docs.birchui.com/spreadsheet/toolbar.md#ribbon-height-classic-single-line-tabs-only): `mode` is `'classic'`, `'simplified'` (one row), `'collapsed'` (tabs only) or `'auto'`. |
| `pasteOptionsButton` | `true` | Show the Paste options button after a paste. |
| `spellcheck` | none | A function `(text, language) => issues` used by [Review > Spelling](https://docs.birchui.com/spreadsheet/data-tools.md#spelling). |
| `datePicker` | `true` | Open a calendar on date cells by double click or `Alt` + `Down`. See [Date picker](https://docs.birchui.com/spreadsheet/data-tools.md#date-picker). |
| `csvImportDialog` | `true` | Ask for delimiter, encoding and locale when a CSV file is opened from the File tab or dropped. |
| `errorChecking` | `true` | Mark numbers stored as text, inconsistent formulas and formulas that omit adjacent cells. See [Error checking](https://docs.birchui.com/spreadsheet/auditing.md#error-checking). |
| `autoComplete` | `true` | Propose the matching entry of the same column while text is typed in a cell. |
| `formulaBar`, `sheetTabs`, `statusBar` | `true` | Show the formula bar with the name box, the sheet tab bar, and the status bar with the selection statistics and the zoom slider. |
| `zoom` | `100` | Zoom in percent, from 10 to 400. |
| `userName` | none | The author recorded on new [comments](https://docs.birchui.com/spreadsheet/notes-and-links.md#threaded-comments) and replies. |
| `headings` | `true` | Show row numbers and column letters. |
| `gridlines` | `true` | Draw cell gridlines. |
| `defaultColumnWidth`, `defaultRowHeight` | `88`, `22` | Default sizes in pixels. |
| `dynamicArrays` | `true` | `false` turns spilling off and uses implicit intersection. |
| `iterativeCalculation` | `false` | `true`, or `{ maxIterations, maxChange }`, for [circular models](https://docs.birchui.com/spreadsheet/formulas.md#circular-references). |
| `now` | the system clock | The time used by `NOW` and `TODAY`. |
| `injectStyles` | `true` | Set `false` and import `@birchui/spreadsheet/styles.css` yourself. |
| `ariaLabel` | `'Spreadsheet'` | The accessible name of the grid. |
| `customLists` | none | Extra [autofill lists](https://docs.birchui.com/spreadsheet/data-tools.md#autofill-series-and-custom-lists), such as `[['North', 'South', 'East', 'West']]`. |
| `resolveImage` | none | Supplies the picture for an [`IMAGE` formula](https://docs.birchui.com/spreadsheet/images.md#the-image-function) as a `data:` or `blob:` URL. Without it `IMAGE` returns `#BLOCKED!`; nothing is fetched. |
| `calculation`, `calculationWorker` | `'sync'` | `'worker'` evaluates formulas in the Web Worker created by `calculationWorker`. See [worker calculation](https://docs.birchui.com/spreadsheet/worker-calculation.md#with-the-spreadsheet-component). |
| `functions` | none | [Custom functions](https://docs.birchui.com/spreadsheet/formulas.md#custom-functions) for formulas, as a map or an array of definitions. |
| `validation` | `'ui'` | `'ui'` checks [data validation](https://docs.birchui.com/spreadsheet/data-tools.md#validation-beyond-typed-input) on typed input only. `'always'` also checks paste, fill, flash fill, replace and API writes. |
| `enforceProtection` | `false` | `true` makes sheet and workbook [protection bind API calls](https://docs.birchui.com/spreadsheet/protection.md#enforcing-protection-in-code) as well as the user interface. |
| `fileDrop` | `true` | Dropping a spreadsheet file on the widget [opens it](https://docs.birchui.com/spreadsheet/toolbar.md#the-file-tab). `false` leaves file drags to the page. |
| `locale`, `localizedFormulas` | en-US | A [locale](https://docs.birchui.com/spreadsheet/formatting.md#locales) for separators, month and day names and typed input: `'de-DE'`, `'fr-FR'`, `'es-ES'` or a locale object. `localizedFormulas: true` also shows and accepts formulas in that locale's syntax. |

`update(partial)` changes options in place. A new `data` loads a workbook and clears the undo history; a new `licenseKey` is verified again; `dynamicArrays`, `iterativeCalculation` and `now` trigger a full recalculation. `calculation` and `calculationWorker` switch between main-thread and [worker calculation](https://docs.birchui.com/spreadsheet/worker-calculation.md#with-the-spreadsheet-component). `functions` replaces the functions that came from the option, and `validation` and `enforceProtection` take effect on the next write.

## Methods

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

```ts
interface SpreadsheetApi extends Widget<SpreadsheetOptions, SpreadsheetEvents>
```

| Property | Type | Description |
| --- | --- | --- |
| `getValue` | `(address: string) => CellValue` |  |
| `setValue` | `(address: string, value: CellInput, options?: WriteOptions) => void` |  |
| `getFormula` | `(address: string) => string \| undefined` |  |
| `setFormula` | `(address: string, formula: string, options?: WriteOptions) => void` |  |
| `getDisplayText` | `(address: string) => string` |  |
| `getRange` | `(range: string) => CellValue[][]` |  |
| `setRange` | `(range: string, values: CellInput[][], options?: WriteOptions) => void` |  |
| `clearRange` | `(range: string, options?: WriteOptions) => void` |  |
| `getStyle` | `(address: string) => CellStyle \| undefined` |  |
| `setStyle` | `(range: string, style: CellStyle \| null, mode?: 'merge' \| 'replace', options?: WriteOptions) => void` |  |
| `getCellControl` | `(address: string) => CellControl \| undefined` |  |
| `setCellControl` | `(range: string, control: CellControl \| null, options?: WriteOptions) => void` |  |
| `mergeCells` | `(range: string, options?: WriteOptions) => void` |  |
| `unmergeCells` | `(range: string, options?: WriteOptions) => void` |  |
| `setColumnWidth` | `(column: number \| string, width: number, options?: WriteOptions) => void` |  |
| `setRowHeight` | `(row: number, height: number, options?: WriteOptions) => void` |  |
| `setFreeze` | `(rows: number, columns: number) => void` |  |
| `splitPanes` | `(cell?: string) => void` |  |
| `removeSplit` | `() => void` |  |
| `insertRows` | `(row: number, count?: number, options?: WriteOptions) => void` |  |
| `deleteRows` | `(row: number, count?: number, options?: WriteOptions) => void` |  |
| `insertColumns` | `(column: number \| string, count?: number, options?: WriteOptions) => void` |  |
| `deleteColumns` | `(column: number \| string, count?: number, options?: WriteOptions) => void` |  |
| `insertCells` | `(range: string, shift?: 'right' \| 'down', options?: WriteOptions) => boolean` |  |
| `deleteCells` | `(range: string, shift?: 'left' \| 'up', options?: WriteOptions) => boolean` |  |
| `sortRange` | `(range: string, column: number \| string, descending?: boolean, options?: WriteOptions) => void` |  |
| `setAutoFilter` | `(range: string \| null, options?: WriteOptions) => void` |  |
| `addConditionalFormat` | `(rule: ConditionalFormat, sheet?: string) => void` |  |
| `clearConditionalFormats` | `(sheet?: string) => void` |  |
| `getConditionalFormats` | `(sheet?: string) => ConditionalFormat[]` |  |
| `setConditionalFormats` | `(rules: ConditionalFormat[], sheet?: string) => void` |  |
| `addValidation` | `(rule: DataValidation, sheet?: string) => void` |  |
| `clearValidations` | `(sheet?: string) => void` |  |
| `find` | `(text: string, options?: FindOptions) => string[]` |  |
| `replaceAll` | `(text: string, replacement: string, options?: FindOptions, writeOptions?: WriteOptions) => number` |  |
| `getSheetNames` | `() => string[]` |  |
| `getActiveSheet` | `() => string` |  |
| `addSheet` | `(name?: string, index?: number, options?: WriteOptions) => string` |  |
| `removeSheet` | `(name: string, options?: WriteOptions) => void` |  |
| `renameSheet` | `(name: string, newName: string, options?: WriteOptions) => void` |  |
| `moveSheet` | `(name: string, index: number, options?: WriteOptions) => void` |  |
| `setSheetHidden` | `(name: string, hidden: boolean, options?: WriteOptions) => void` |  |
| `setActiveSheet` | `(name: string) => void` |  |
| `defineName` | `(name: string, formula: string, sheet?: string) => void` |  |
| `formatEditorSelection` | `(format: EditorTextFormat) => boolean` |  |
| `undo` | `() => boolean` |  |
| `redo` | `() => boolean` |  |
| `canUndo` | `() => boolean` |  |
| `canRedo` | `() => boolean` |  |
| `recalculate` | `() => RecalculatedEvent` |  |
| `getCalculationMode` | `() => CalculationMode` |  |
| `getRibbonMode` | `() => { mode: RibbonMode; resolved: RibbonLayout }` |  |
| `whenCalculated` | `() => Promise<void>` |  |
| `registerFunction` | `(name: string, impl: CustomFunctionImpl, options?: CustomFunctionOptions) => void` |  |
| `unregisterFunction` | `(name: string) => boolean` |  |
| `listFunctions` | `() => FunctionInfo[]` |  |
| `select` | `(range: string) => void` |  |
| `goTo` | `(reference: string) => boolean` |  |
| `selectSpecial` | `(kind: GoToSpecialKind, range?: string) => string[]` |  |
| `getSelection` | `() => SelectionChangeEvent` |  |
| `importXlsx` | `(data: Uint8Array \| ArrayBuffer \| Blob, options?: XlsxOpenOptions) => Promise<void>` |  |
| `importCsv` | `(data: string \| Uint8Array \| ArrayBuffer, options?: CsvImportOptions) => void` |  |
| `exportCsv` | `(options?: CsvExportOptions) => string` |  |
| `importOds` | `(data: Uint8Array \| ArrayBuffer, options?: OdsImportOptions) => Promise<void>` |  |
| `exportOds` | `(options?: OdsExportOptions) => Promise<Uint8Array>` |  |
| `exportXlsx` | `(options?: XlsxExportOptions) => Promise<Uint8Array>` |  |
| `downloadXlsx` | `(fileName: string) => Promise<void>` |  |
| `exportPdf` | `(options?: PdfExportOptions) => Promise<Uint8Array>` |  |
| `downloadPdf` | `(fileName: string, options?: PdfExportOptions) => Promise<void>` |  |
| `openFile` | `(file: Blob \| Uint8Array \| ArrayBuffer, fileName?: string, options?: FileOpenOptions) => Promise<boolean>` |  |
| `saveAs` | `(format: FileSaveFormat, fileName?: string) => Promise<boolean>` |  |
| `getFileName` | `() => string` |  |
| `toJSON` | `() => WorkbookJSON` |  |
| `fromJSON` | `(json: WorkbookJSON) => void` |  |
| `getNames` | `() => DefinedNameInfo[]` |  |
| `removeName` | `(name: string, sheet?: string) => boolean` |  |
| `setNote` | `(address: string, note: string \| CellNote \| null) => void` |  |
| `getNote` | `(address: string) => CellNote \| undefined` |  |
| `getNotes` | `(sheet?: string) => Record<string, CellNote>` |  |
| `setHyperlink` | `(address: string, link: string \| Hyperlink \| null) => void` |  |
| `getHyperlink` | `(address: string) => Hyperlink \| undefined` |  |
| `followHyperlink` | `(address: string) => boolean` |  |
| `protectSheet` | `(options?: ProtectSheetOptions, sheet?: string) => void` |  |
| `unprotectSheet` | `(password?: string, sheet?: string) => boolean` |  |
| `isSheetProtected` | `(sheet?: string) => boolean` |  |
| `protectWorkbook` | `(password?: string) => void` |  |
| `unprotectWorkbook` | `(password?: string) => boolean` |  |
| `isWorkbookProtected` | `() => boolean` |  |
| `isCellLocked` | `(address: string) => boolean` |  |
| `addTable` | `(range: string, options?: TableOptions) => string` |  |
| `removeTable` | `(name: string) => void` |  |
| `getTables` | `(sheet?: string) => TableJSON[]` |  |
| `getTable` | `(name: string) => TableJSON \| undefined` |  |
| `updateTable` | `(name: string, changes: Partial<Omit<TableJSON, 'name' \| 'range' \| 'columns'>> & { name?: string }) => void` |  |
| `resizeTable` | `(name: string, range: string) => void` |  |
| `groupRows` | `(first: number, last: number) => void` |  |
| `ungroupRows` | `(first: number, last: number) => void` |  |
| `groupColumns` | `(first: number \| string, last: number \| string) => void` |  |
| `ungroupColumns` | `(first: number \| string, last: number \| string) => void` |  |
| `collapseGroup` | `(axis: 'rows' \| 'columns', index: number \| string) => void` |  |
| `expandGroup` | `(axis: 'rows' \| 'columns', index: number \| string) => void` |  |
| `showOutlineLevel` | `(axis: 'rows' \| 'columns', level: number) => void` |  |
| `addImage` | `(image: Omit<ImageJSON, 'id'> & { id?: string }, sheet?: string) => string` |  |
| `updateImage` | `(id: string, changes: Partial<Omit<ImageJSON, 'id'>>) => void` |  |
| `removeImage` | `(id: string) => void` |  |
| `getImages` | `(sheet?: string) => ImageJSON[]` |  |
| `addChart` | `(chart: Omit<ChartJSON, 'id'> & { id?: string }, sheet?: string) => string` |  |
| `updateChart` | `(id: string, changes: Partial<Omit<ChartJSON, 'id'>>) => void` |  |
| `removeChart` | `(id: string) => void` |  |
| `getCharts` | `(sheet?: string) => ChartJSON[]` |  |
| `addSparklines` | `(group: SparklineGroup, sheet?: string) => void` |  |
| `clearSparklines` | `(range?: string, sheet?: string) => void` |  |
| `getSparklines` | `(sheet?: string) => SparklineGroup[]` |  |
| `setPageSetup` | `(setup: PageSetup \| null, sheet?: string) => void` |  |
| `getPageSetup` | `(sheet?: string) => PageSetup \| undefined` |  |
| `setPageBreak` | `(axis: 'row' \| 'column', index: number \| string, on?: boolean) => void` |  |
| `print` | `(options?: PrintOptions) => void` |  |
| `getPrintHtml` | `(options?: PrintOptions) => string` |  |
| `getPrecedents` | `(address: string) => string[]` |  |
| `getDependents` | `(address: string) => string[]` |  |
| `tracePrecedents` | `(address?: string) => void` |  |
| `traceDependents` | `(address?: string) => void` |  |
| `clearArrows` | `() => void` |  |
| `evaluateFormulaSteps` | `(address: string) => FormulaStep[]` |  |
| `listCellStyles` | `() => NamedCellStyle[]` |  |
| `applyCellStyle` | `(range: string, name: string, options?: WriteOptions) => void` |  |
| `autoSum` | `(range?: string, options?: WriteOptions) => void` |  |
| `openDialog` | `(dialog: SpreadsheetDialog) => void` |  |
| `setComment` | `(address: string, comment: string \| CommentThread \| null) => void` |  |
| `getComment` | `(address: string) => CommentThread \| undefined` |  |
| `getComments` | `(sheet?: string) => Record<string, CommentThread>` |  |
| `addCommentReply` | `(address: string, reply: string \| CommentReply) => void` |  |
| `resolveComment` | `(address: string, resolved?: boolean) => void` |  |
| `insertPivotTable` | `(definition: PivotTableOptions, sheet?: string) => string` |  |
| `updatePivotTable` | `(name: string, changes: Partial<Omit<PivotTableJSON, 'name' \| 'range'>>) => void` |  |
| `refreshPivotTable` | `(name?: string) => void` |  |
| `removePivotTable` | `(name: string) => void` |  |
| `getPivotTables` | `(sheet?: string) => PivotTableJSON[]` |  |
| `drillDownPivot` | `(address: string) => string \| undefined` |  |
| `addSlicer` | `(slicer: Omit<SlicerJSON, 'id'> & { id?: string }, sheet?: string) => string` |  |
| `updateSlicer` | `(id: string, changes: Partial<Omit<SlicerJSON, 'id'>>) => void` |  |
| `removeSlicer` | `(id: string) => void` |  |
| `getSlicers` | `(sheet?: string) => SlicerJSON[]` |  |
| `addShape` | `(shape: Omit<ShapeJSON, 'id'> & { id?: string }, sheet?: string) => string` |  |
| `updateShape` | `(id: string, changes: Partial<Omit<ShapeJSON, 'id'>>) => void` |  |
| `removeShape` | `(id: string) => void` |  |
| `getShapes` | `(sheet?: string) => ShapeJSON[]` |  |
| `insertEmbeddedObject` | `(object: EmbeddedObjectInput, sheet?: string) => string` |  |
| `updateEmbeddedObject` | `(id: string, changes: EmbeddedObjectChanges) => void` |  |
| `removeEmbeddedObject` | `(id: string) => void` |  |
| `getEmbeddedObjects` | `(sheet?: string) => EmbeddedObjectJSON[]` |  |
| `getEmbeddedObjectData` | `(id: string) => Uint8Array \| undefined` |  |
| `getEmbeddedObjectType` | `(id: string) => EmbeddedFileType \| undefined` |  |
| `openEmbeddedObject` | `(id: string) => void` |  |
| `downloadEmbeddedObject` | `(id: string) => boolean` |  |
| `setCellImage` | `(address: string, image: CellImage \| null) => void` |  |
| `getCellImage` | `(address: string) => CellImage \| undefined` |  |
| `sortRangeBy` | `(range: string, levels: SortLevel[], options?: SortOptions, writeOptions?: WriteOptions) => void` |  |
| `removeDuplicates` | `(range: string, options?: RemoveDuplicatesOptions, writeOptions?: WriteOptions) => number` |  |
| `textToColumns` | `(range: string, options?: TextToColumnsOptions, writeOptions?: WriteOptions) => void` |  |
| `flashFill` | `(range?: string, options?: WriteOptions) => number` |  |
| `subtotal` | `(range: string, options: SubtotalOptions, writeOptions?: WriteOptions) => void` |  |
| `removeSubtotals` | `(range: string, options?: WriteOptions) => void` |  |
| `goalSeek` | `(options: GoalSeekOptions) => GoalSeekResult` |  |
| `addDataTable` | `(table: DataTableJSON) => void` |  |
| `removeDataTable` | `(range: string, options?: RemoveDataTableOptions) => boolean` |  |
| `getDataTables` | `(sheet?: string) => DataTableInfo[]` |  |
| `setColumnFilter` | `(column: number \| string, condition: FilterCondition \| null) => void` |  |
| `pasteSpecial` | `(options?: PasteSpecialOptions, writeOptions?: WriteOptions) => void` |  |
| `pasteValues` | `(writeOptions?: WriteOptions) => boolean` |  |
| `getPasteOptions` | `() => { current: PasteOption; available: PasteOption[] } \| undefined` |  |
| `checkSpelling` | `(range?: string) => Promise<SpellingMatch[]>` |  |
| `getSpellingIssues` | `() => SpellingMatch[]` |  |
| `replaceSpelling` | `(match: Pick<SpellingMatch, 'sheet' \| 'address' \| 'from' \| 'to'>, text: string) => boolean` |  |
| `ignoreSpelling` | `(word: string) => void` |  |
| `getSheetViews` | `(sheet?: string) => SheetViewInfo[]` |  |
| `saveSheetView` | `(name: string, sheet?: string) => string \| undefined` |  |
| `applySheetView` | `(name: string \| null, sheet?: string) => boolean` |  |
| `deleteSheetView` | `(name: string, sheet?: string) => boolean` |  |
| `getErrorChecks` | `(sheet?: string) => ErrorCheckInfo[]` |  |
| `ignoreError` | `(address: string, kind?: ErrorCheckKind) => void` |  |
| `applyPasteOption` | `(option: PasteOption, writeOptions?: WriteOptions) => boolean` |  |
| `setFormatPainter` | `(mode: boolean \| 'locked') => void` |  |
| `setZoom` | `(percent: number) => void` |  |
| `getZoom` | `() => number` |  |
| `hideRows` | `(first: number, last?: number, options?: WriteOptions) => void` |  |
| `unhideRows` | `(first: number, last?: number, options?: WriteOptions) => void` |  |
| `hideColumns` | `(first: number \| string, last?: number \| string, options?: WriteOptions) => void` |  |
| `unhideColumns` | `(first: number \| string, last?: number \| string, options?: WriteOptions) => void` |  |
| `duplicateSheet` | `(name: string, newName?: string, options?: WriteOptions) => string` |  |
| `setTabColor` | `(name: string, color: string \| null) => void` |  |
| `getSheetView` | `(sheet?: string) => SheetView` |  |
| `setSheetView` | `(view: Partial<SheetView>, sheet?: string) => void` |  |
| `onOperation` | `(listener: (event: SheetOperationEvent) => void) => () => void` |  |
| `applyRemoteOperation` | `(operation: SheetOperation) => boolean` |  |
| `setPresence` | `(cursors: PresenceCursor[]) => void` |  |
| `getPresence` | `() => PresenceCursor[]` |  |
| `getImportReport` | `() => XlsxImportReport \| undefined` |  |
| `getProperties` | `() => DocumentProperties` |  |
| `setProperties` | `(properties: Partial<DocumentProperties>) => void` |  |
| `readonly element` | `HTMLElement` | Inherited from Widget. |
| `update` | `(options: Partial<SpreadsheetOptions>) => void` | Inherited from Widget. |
| `on` | `<K extends keyof TEvents & string>(event: K, listener: Listener<TEvents[K]>) => () => void` | Inherited from Widget. |
| `destroy` | `() => void` | Inherited from Widget. |

### Cells

| Method | Purpose |
| --- | --- |
| `getValue(address)`, `setValue(address, value)` | Read or write one cell. Strings are interpreted like [typed input](https://docs.birchui.com/spreadsheet/formulas.md#entering-values-and-formulas); a `Date` becomes a date serial. |
| `getFormula(address)`, `setFormula(address, formula)` | Read or write a formula. |
| `getDisplayText(address)` | The text the cell shows, with its number format applied. |
| `getRange(range)`, `setRange(range, values)` | Read or write a block with a 2D array. `setRange` needs only the top-left cell and recalculates once. |
| `clearRange(range)` | Clear values and formulas, keeping formatting. |

Addresses and ranges accept a sheet prefix, such as `'Q3 Budget'!B4`, or a defined name; without one they refer to the active sheet.

### Write options

The methods that change cells, formatting, structure or sheets take an optional last argument, `{ force?: boolean }`. It matters only with [`validation: 'always'`](https://docs.birchui.com/spreadsheet/data-tools.md#validation-beyond-typed-input), with [`enforceProtection: true`](https://docs.birchui.com/spreadsheet/protection.md#enforcing-protection-in-code), or while the workbook structure is protected: `force: true` makes that one call skip those checks.

```ts
sheet.setValue('B4', 1250, { force: true });
sheet.setStyle('A1:F1', { bold: true }, 'merge', { force: true });
sheet.insertRows(12, 3, { force: true });
```

The argument comes after the method's other arguments, so the optional ones before it must be given or passed as `undefined`: `addSheet('Actuals', undefined, { force: true })`.

| Group | Methods that take `{ force }` |
| --- | --- |
| Cells | `setValue`, `setFormula`, `setRange`, `clearRange`, `replaceAll`, `autoSum`, `flashFill`, `textToColumns`, `removeDuplicates`, `subtotal`, `removeSubtotals`, `pasteSpecial`, `pasteValues`, `applyPasteOption` |
| Formatting | `setStyle`, `setCellControl`, `applyCellStyle`, `mergeCells`, `unmergeCells`, `setColumnWidth`, `setRowHeight`, `hideRows`, `unhideRows`, `hideColumns`, `unhideColumns` |
| Structure | `insertRows`, `deleteRows`, `insertColumns`, `deleteColumns`, `insertCells`, `deleteCells`, `sortRange`, `sortRangeBy`, `setAutoFilter` |
| Sheets | `addSheet`, `removeSheet`, `renameSheet`, `moveSheet`, `setSheetHidden`, `duplicateSheet` |

A blocked call throws a `ValidationError` or a `ProtectionError`, both exported from the package, and changes nothing.

### Formatting and layout

| Method | Purpose |
| --- | --- |
| `getStyle(address)`, `setStyle(range, style, mode?)` | Read or write [styles](https://docs.birchui.com/spreadsheet/formatting.md#cell-styles). |
| `getCellControl(address)`, `setCellControl(range, control)` | Read or set the [cell control](https://docs.birchui.com/spreadsheet/formatting.md#cell-controls): `'checkbox'`, `'dropdown'` or `null` to remove it. |
| `formatEditorSelection(format)` | Format the text selected in the open cell editor as [rich text](https://docs.birchui.com/spreadsheet/formatting.md#rich-text). Returns `false` when no text edit is open. |
| `mergeCells(range)`, `unmergeCells(range)` | Merge and unmerge. |
| `setColumnWidth(column, width)`, `setRowHeight(row, height)` | Sizes in pixels; columns by letter or 1-based number, rows by 1-based number. |
| `setFreeze(rows, columns)` | Freeze panes on the active sheet; `0, 0` unfreezes. |
| `splitPanes(cell?)`, `removeSplit()` | Split the grid above and left of a cell into [panes that scroll on their own](https://docs.birchui.com/spreadsheet/sheets.md#split-panes), or remove the split. |

### Structure and data

| Method | Purpose |
| --- | --- |
| `insertRows(row, count?)`, `deleteRows(row, count?)` | Insert or delete rows at a 1-based row on the active sheet. |
| `goTo(reference)`, `selectSpecial(kind, range?)` | Select a cell, range, list of ranges or defined name; select the cells of one kind (`'blanks'`, `'constants'`, `'formulas'`, `'errors'`, `'visibleCells'`, `'currentRegion'`, `'conditionalFormats'`, `'dataValidation'`, `'notes'`, `'lastCell'`) and return the selected ranges. |
| `insertCells(range, shift?)`, `deleteCells(range, shift?)` | Insert blank cells at `range` and push the existing ones `'down'` (default) or `'right'`, or delete the cells of `range` and pull the following ones `'up'` (default) or `'left'`. Only the columns (or rows) of the range move. Returns `false` when the sheet is read-only or protected, or when the range would cut a merged cell, a table, a filtered range, a PivotTable or a data table in two; the `error` event says which. |
| `insertColumns(column, count?)`, `deleteColumns(column, count?)` | The same for columns, by letter or 1-based number. |
| `sortRange(range, column, descending?)` | [Sort](https://docs.birchui.com/spreadsheet/data-tools.md#sort) a range by one column. |
| `setAutoFilter(range)` | Turn on an [autofilter](https://docs.birchui.com/spreadsheet/data-tools.md#autofilter), or pass `null` to remove it. |
| `addConditionalFormat(rule, sheet?)`, `clearConditionalFormats(sheet?)`, `getConditionalFormats(sheet?)`, `setConditionalFormats(rules, sheet?)` | [Conditional formatting](https://docs.birchui.com/spreadsheet/formatting.md#conditional-formatting). |
| `addValidation(rule, sheet?)`, `clearValidations(sheet?)` | [Data validation](https://docs.birchui.com/spreadsheet/data-tools.md#data-validation). |
| `find(text, options?)`, `replaceAll(text, replacement, options?)` | [Find and replace](https://docs.birchui.com/spreadsheet/data-tools.md#find-and-replace). |

### Sheets and names

| Method | Purpose |
| --- | --- |
| `getSheetNames()`, `getActiveSheet()`, `setActiveSheet(name)` | List and switch sheets. |
| `addSheet(name?, index?)`, `removeSheet(name)`, `renameSheet(name, newName)`, `moveSheet(name, index)`, `setSheetHidden(name, hidden)` | Manage [sheets](https://docs.birchui.com/spreadsheet/sheets.md#sheets-in-code). |
| `duplicateSheet(name, newName?)` | [Copy a sheet](https://docs.birchui.com/spreadsheet/sheets.md#duplicating-a-sheet) next to the original; returns the name of the copy. Throws when the new name is invalid or taken. |
| `setTabColor(name, color)` | Set the tab colour, or remove it with `null`. |
| `getSheetView(sheet?)`, `setSheetView(view, sheet?)` | Read and change the [sheet view](https://docs.birchui.com/spreadsheet/sheets.md#sheet-views): zoom, gridlines, headings, direction and zero values. A key set to `undefined` is removed. |
| `defineName(name, formula, sheet?)` | Add or change a [defined name](https://docs.birchui.com/spreadsheet/formulas.md#defined-names). |

### Selection, history and calculation

| Method | Purpose |
| --- | --- |
| `select(range)`, `getSelection()` | Select a range, switching sheet if needed and scrolling it into view; read the selection. |
| `undo()`, `redo()`, `canUndo()`, `canRedo()` | [Undo and redo](https://docs.birchui.com/spreadsheet/data-tools.md#undo-and-redo). |
| `recalculate()` | Recalculate every formula, calling async custom functions again. Returns `{ changedCount, ms }`. |
| `whenCalculated()` | A promise that resolves when no calculation is outstanding. It resolves at once unless [worker calculation](https://docs.birchui.com/spreadsheet/worker-calculation.md#with-the-spreadsheet-component) is on or an [async custom function](https://docs.birchui.com/spreadsheet/formulas.md#async-functions) is pending. |
| `registerFunction(name, impl, options?)`, `unregisterFunction(name)` | Add or remove a [custom function](https://docs.birchui.com/spreadsheet/formulas.md#custom-functions) on this spreadsheet. `registerFunction` throws for an invalid name. |
| `listFunctions()` | The built-in functions plus this spreadsheet's custom ones, which have `category: 'custom'`. |
| `getCalculationMode()` | `'sync'` or `'worker'`: where formulas are evaluated right now. |
| `getRibbonMode()` | `{ mode, resolved }`: the ribbon mode asked for and the layout on screen. |

### Tables, outline and protection

| Method | Purpose |
| --- | --- |
| `addTable(range, options?)`, `removeTable(name)`, `updateTable(name, changes)`, `resizeTable(name, range)` | Create and manage [tables](https://docs.birchui.com/spreadsheet/tables.md). `removeTable` converts the table to a plain range. |
| `getTables(sheet?)`, `getTable(name)` | Read tables as `TableJSON`. |
| `groupRows(first, last)`, `ungroupRows(first, last)`, `groupColumns(first, last)`, `ungroupColumns(first, last)` | [Outline grouping](https://docs.birchui.com/spreadsheet/outline.md). |
| `collapseGroup(axis, index)`, `expandGroup(axis, index)`, `showOutlineLevel(axis, level)` | Collapse and expand groups, or show one outline level. |
| `protectSheet(options?, sheet?)`, `unprotectSheet(password?, sheet?)`, `isSheetProtected(sheet?)` | [Sheet protection](https://docs.birchui.com/spreadsheet/protection.md). Passwords are stored only as salted SHA-512 hashes. |
| `protectWorkbook(password?)`, `unprotectWorkbook(password?)`, `isWorkbookProtected()`, `isCellLocked(address)` | Workbook structure protection and cell lock state. |

### Notes, links and drawings

| Method | Purpose |
| --- | --- |
| `setNote(address, note)`, `getNote(address)`, `getNotes(sheet?)` | [Notes](https://docs.birchui.com/spreadsheet/notes-and-links.md). Pass `null` to remove one. |
| `setHyperlink(address, link)`, `getHyperlink(address)`, `followHyperlink(address)` | Web, email and in-workbook [hyperlinks](https://docs.birchui.com/spreadsheet/notes-and-links.md#hyperlinks). |
| `addImage(image, sheet?)`, `updateImage(id, changes)`, `removeImage(id)`, `getImages(sheet?)` | [Pictures](https://docs.birchui.com/spreadsheet/images.md) from `data:` or `blob:` URLs. |
| `setCellImage(address, image)`, `getCellImage(address)` | [Pictures in cells](https://docs.birchui.com/spreadsheet/images.md#pictures-in-cells). Pass `null` to remove one. |
| `insertEmbeddedObject(object, sheet?)`, `updateEmbeddedObject(id, changes)`, `removeEmbeddedObject(id)`, `getEmbeddedObjects(sheet?)`, `getEmbeddedObjectData(id)`, `getEmbeddedObjectType(id)`, `openEmbeddedObject(id)`, `downloadEmbeddedObject(id)` | [Embedded files](https://docs.birchui.com/spreadsheet/embedded-objects.md) and the [type detected](https://docs.birchui.com/spreadsheet/embedded-objects.md#file-types) for each. |
| `addChart(chart, sheet?)`, `updateChart(id, changes)`, `removeChart(id)`, `getCharts(sheet?)` | [Charts](https://docs.birchui.com/spreadsheet/charts.md) that follow their source ranges. |
| `addSparklines(group, sheet?)`, `clearSparklines(range?, sheet?)`, `getSparklines(sheet?)` | [Sparklines](https://docs.birchui.com/spreadsheet/sparklines.md). |

### Printing, auditing and tools

| Method | Purpose |
| --- | --- |
| `setPageSetup(setup, sheet?)`, `getPageSetup(sheet?)`, `setPageBreak(axis, index, on?)` | [Page setup](https://docs.birchui.com/spreadsheet/printing.md), print area, titles and manual page breaks. |
| `print(options?)`, `getPrintHtml(options?)` | Print through the browser, or get standalone print HTML. |
| `getPrecedents(address)`, `getDependents(address)` | Direct precedents and dependents as addresses. |
| `tracePrecedents(address?)`, `traceDependents(address?)`, `clearArrows()` | [Trace arrows](https://docs.birchui.com/spreadsheet/auditing.md) on the grid. |
| `evaluateFormulaSteps(address)` | The steps of Evaluate Formula, as `{ formula, evaluated, value }`. |
| `listCellStyles()`, `applyCellStyle(range, name)` | The [cell styles gallery](https://docs.birchui.com/spreadsheet/formatting.md#cell-styles-gallery). |
| `autoSum(range?)` | Insert `SUM` like `Alt` + `=`. |
| `openDialog(dialog)` | Open a built-in dialog or panel. The names are listed under [keyboard shortcuts](https://docs.birchui.com/spreadsheet/keyboard.md#data-structure-and-tools). |
| `getNames()`, `removeName(name, sheet?)` | List and delete defined names. |
| `getProperties()`, `setProperties(properties)` | The document properties of the workbook (`title`, `subject`, `author`, `manager`, `company`, `category`, `keywords`, `status`, `description` and more, see `DocumentProperties`). `setProperties` merges the given keys, removes a key set to an empty string, and is one undo step. The same data is in `WorkbookJSON.properties` and in the **Review > Properties** dialog. |

### Comments

| Method | Purpose |
| --- | --- |
| `setComment(address, comment)`, `getComment(address)`, `getComments(sheet?)` | [Threaded comments](https://docs.birchui.com/spreadsheet/notes-and-links.md#threaded-comments). Pass text, a full thread, or `null` to delete. |
| `addCommentReply(address, reply)`, `resolveComment(address, resolved?)` | Reply to a thread, and resolve or reopen it. |

### Pivot tables, slicers and shapes

| Method | Purpose |
| --- | --- |
| `insertPivotTable(definition, sheet?)`, `updatePivotTable(name, changes)`, `refreshPivotTable(name?)`, `removePivotTable(name)`, `getPivotTables(sheet?)` | [Pivot tables](https://docs.birchui.com/spreadsheet/pivot-tables.md). |
| `drillDownPivot(address)` | Add a sheet with the source rows behind a pivot value; returns its name. |
| `addSlicer(slicer, sheet?)`, `updateSlicer(id, changes)`, `removeSlicer(id)`, `getSlicers(sheet?)` | [Slicers](https://docs.birchui.com/spreadsheet/slicers.md). |
| `addShape(shape, sheet?)`, `updateShape(id, changes)`, `removeShape(id)`, `getShapes(sheet?)` | [Shapes and text boxes](https://docs.birchui.com/spreadsheet/shapes.md). |

### Data tools and view

| Method | Purpose |
| --- | --- |
| `sortRangeBy(range, levels, options?)` | [Multi-level sort](https://docs.birchui.com/spreadsheet/data-tools.md#multi-level-sort) with custom lists. |
| `setColumnFilter(column, condition)` | [Filter](https://docs.birchui.com/spreadsheet/data-tools.md#filter-by-condition-rank-colour-or-date) a column by condition, rank, colour, date or values; `null` clears it. |
| `removeDuplicates(range, options?)` | Remove repeated rows; returns how many were removed. |
| `textToColumns(range, options?)` | Split one column into several. |
| `flashFill(range?)` | Fill a column from the pattern of your examples; returns the number of cells filled. |
| `subtotal(range, options)`, `removeSubtotals(range)` | Insert or remove subtotal rows with an outline. |
| `goalSeek(options)` | Find the input that makes a formula reach a target. |
| `addDataTable(table)`, `removeDataTable(range, options?)`, `getDataTables(sheet?)` | [Data tables](https://docs.birchui.com/spreadsheet/data-tools.md#data-tables) for what-if analysis with one or two input cells. |
| `pasteSpecial(options?)`, `setFormatPainter(mode)` | Paste values, formulas or formats, optionally transposed; turn the format painter on, off or `'locked'`. |
| `pasteValues()`, `getPasteOptions()`, `applyPasteOption(option)` | Paste the copied cells as values; read the options of the paste that was just made (`{ current, available }`, or `undefined` once the workbook changed again); rewrite that paste as `'all'`, `'values'`, `'formulas'`, `'formats'`, `'transpose'`, `'columnWidths'` or `'link'`. |
| `hideRows(first, last?)`, `unhideRows(first, last?)`, `hideColumns(first, last?)`, `unhideColumns(first, last?)` | Hide and show rows and columns. |
| `setZoom(percent)`, `getZoom()` | Zoom the grid. |

### Files

| Method | Purpose |
| --- | --- |
| `toJSON()`, `fromJSON(json)` | Save and load the [workbook JSON](https://docs.birchui.com/spreadsheet/sheets.md#the-workbook-json). |
| `importXlsx(data, options?)` | Load an [Excel file](https://docs.birchui.com/spreadsheet/xlsx.md) from a `Blob`, `File`, `ArrayBuffer` or `Uint8Array`. A [legacy `.xls` file](https://docs.birchui.com/spreadsheet/file-formats.md#legacy-xls-files) is recognised by its content and opened too. The options are `password` for an [encrypted file](https://docs.birchui.com/spreadsheet/encryption.md), `onProgress` and `signal` to [follow or cancel the import](https://docs.birchui.com/spreadsheet/xlsx.md#progress-and-cancelling), and `limits` and `xlsLimits`. |
| `exportXlsx(options?)`, `downloadXlsx(fileName)` | Write an Excel file as a `Uint8Array`, or download it. The options are `compress` and `password`, which [encrypts the file](https://docs.birchui.com/spreadsheet/encryption.md). |
| `importCsv(data, options?)`, `exportCsv(options?)` | Load [CSV or TSV](https://docs.birchui.com/spreadsheet/file-formats.md#csv-and-tsv) text or bytes as a one-sheet workbook; return the active sheet, or the one named in `sheet`, as CSV text. Both are synchronous. |
| `importOds(data, options?)`, `exportOds(options?)` | Load and write [OpenDocument spreadsheets](https://docs.birchui.com/spreadsheet/file-formats.md#opendocument-spreadsheets). Both return promises. |
| `exportPdf(options?)`, `downloadPdf(fileName, options?)` | Write a [vector PDF](https://docs.birchui.com/spreadsheet/printing.md#export-to-pdf) of the active sheet, or of the sheets named in `sheets`, as a `Uint8Array`, or download it. No print dialog. |
| `openFile(file, fileName?, options?)`, `saveAs(format, fileName?)`, `getFileName()` | What the [File tab](https://docs.birchui.com/spreadsheet/toolbar.md#the-file-tab) does: open an xlsx, xls, CSV or ods file after detecting its format (`options.password` opens a password-protected xlsx without a dialog), and download the workbook as `'xlsx'`, `'csv'`, `'ods'` or `'pdf'`. Both fire a cancellable event first and resolve to `false` when a listener cancelled. `getFileName()` is the name of the opened file without its extension, `workbook` until a file is opened. |
| `getImportReport()` | The report of the last `importXlsx()`: `{ modelled, preserved, dropped }`, each a list of `{ feature, sheet?, count?, parts?, elements?, note? }`. `modelled` is what was read into the workbook and can be edited, `preserved` is kept unchanged for export, `dropped` is not kept. It is `undefined` before the first import and after `fromJSON()` or `update({ data })`. **Review > Import report** and `openDialog('importReport')` show it. |

### Collaboration

| Method | Purpose |
| --- | --- |
| `onOperation(listener)` | Call `listener({ operation, origin: 'local' })` for every local edit, including undo and redo. Returns a function that stops listening. See [Operations](https://docs.birchui.com/spreadsheet/collaboration.md#operations). |
| `applyRemoteOperation(operation)` | Apply an operation from another user without emitting it and without an undo step. Returns `false`, and fires `error` with `code: 'collaboration'`, when the operation is invalid or does not fit the workbook. |
| `setPresence(cursors)`, `getPresence()` | Draw and read other users' [cursors](https://docs.birchui.com/spreadsheet/collaboration.md#presence): `{ id, name, color?, sheet, active, ranges? }`. |

Like every Birch UI widget, the API also has `element`, `update(partial)`, `on(event, listener)` and `destroy()`. Changes made through the API are undoable, like user edits.

## Events

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

```ts
interface SpreadsheetEvents
```

| Property | Type | Description |
| --- | --- | --- |
| `ready` | `{ api: SpreadsheetApi }` |  |
| `cellChange` | `CellChangeEvent` |  |
| `selectionChange` | `SelectionChangeEvent` |  |
| `sheetChange` | `SheetChangeEvent` |  |
| `recalculated` | `RecalculatedEvent` |  |
| `error` | `SpreadsheetErrorEvent` |  |
| `hyperlinkClick` | `HyperlinkClickEvent` |  |
| `mention` | `MentionEvent` |  |
| `viewportScroll` | `{ sheet: string; top: number; left: number; firstRow: number; firstColumn: number }` |  |
| `zoomChange` | `{ zoom: number }` |  |
| `pivotTableRefreshed` | `{ sheet: string; name: string; range: string }` |  |
| `importReport` | `{ report: XlsxImportReport }` |  |
| `embeddedObjectOpen` | `EmbeddedObjectOpenEvent` |  |
| `beforeOpen` | `BeforeOpenEvent` |  |
| `beforeSave` | `BeforeSaveEvent` |  |
| `ribbonModeChange` | `RibbonModeChangeEvent` |  |

| Event | Payload | When |
| --- | --- | --- |
| `ready` | `{ api }` | Once, right after creation. |
| `cellChange` | `{ sheet, address, oldValue, newValue, formula?, source }` | A cell's content changed. `source` is `edit`, `api`, `paste`, `fill`, `undo`, `redo`, `replace`, `clear`, `sort` or `remote` (an operation from [another user](https://docs.birchui.com/spreadsheet/collaboration.md)). Not fired for cells that only recalculated. |
| `selectionChange` | `{ sheet, active, ranges }` | The selection moved. `active` is the active cell, `ranges` the selected ranges. |
| `sheetChange` | `{ sheet, action, previous? }` | A sheet was activated, added, removed, renamed, moved, hidden or shown. |
| `recalculated` | `{ changedCount, ms }` | A recalculation finished. |
| `error` | `{ code, message, sheet?, address? }` | Something the user should know about, see below. |
| `hyperlinkClick` | `{ sheet, address, url?, location?, preventDefault() }` | A hyperlink is about to be followed. Call `preventDefault()` to handle it yourself. |
| `viewportScroll` | `{ sheet, top, left, firstRow, firstColumn }` | The grid scrolled. |
| `zoomChange` | `{ zoom }` | The zoom level changed, in percent. Also fired when a sheet with a different [zoom of its own](https://docs.birchui.com/spreadsheet/sheets.md#sheet-views) is activated. |
| `pivotTableRefreshed` | `{ sheet, name, range }` | A pivot table rewrote its cells. |
| `embeddedObjectOpen` | `{ sheet, id, fileName, mimeType, progId, fileType, data }` | The user opened an [embedded file](https://docs.birchui.com/spreadsheet/embedded-objects.md#opening-and-downloading), or `openEmbeddedObject()` was called. `data` holds the file bytes; `fileName`, `mimeType` and `fileType` come from the [detected type](https://docs.birchui.com/spreadsheet/embedded-objects.md#file-types). |
| `importReport` | `{ report }` | `importXlsx()` finished. `report` holds the same lists `getImportReport()` returns. Not fired by `importCsv()` or `importOds()`. |
| `beforeOpen` | `{ fileName, format, data, source, preventDefault() }` | A file is about to be opened from the File tab (`source: 'picker'`), by a drop (`'drop'`) or by `openFile()` (`'api'`). `format` is `'xlsx'`, `'xls'`, `'csv'` or `'ods'`; `data` holds the bytes. `preventDefault()` leaves the workbook as it is. |
| `beforeSave` | `{ fileName, format, preventDefault() }` | A download is about to start from the File tab or `saveAs()`. `format` is `'xlsx'`, `'csv'`, `'ods'` or `'pdf'`. `preventDefault()` stops it, so you can save the bytes yourself. Not fired by `downloadXlsx()` and `downloadPdf()`. |
| `ribbonModeChange` | `{ mode, resolved, source }` | The ribbon layout changed through the display menu, `Ctrl` + `F1` or a double click on a tab (`source: 'user'`), or `'auto'` picked another layout after a resize (`source: 'resize'`). Not fired by `update()`. |

```ts
sheet.on('selectionChange', ({ active, ranges }) => {
  selectionLabel.textContent = `${active} (${ranges.join(', ')})`;
});
```

Errors thrown by your listeners are caught and logged with `console.error`, so they cannot break the spreadsheet.

### Error codes

| `code` | Cause |
| --- | --- |
| `circularReference` | A formula refers to itself, directly or indirectly. |
| `validation` | Input broke a [validation rule](https://docs.birchui.com/spreadsheet/data-tools.md#data-validation). With `validation: 'always'` this also covers a rejected API write and cells skipped by a paste, fill or replace. |
| `formula` | A command could not run: a formula with a syntax error, an unknown reference in the name box, an invalid sheet name, removing or hiding the last visible sheet, a command on a multiple selection, or blocked clipboard access. Also a [custom function](https://docs.birchui.com/spreadsheet/formulas.md#custom-functions) that threw or whose promise rejected; `sheet` and `address` name the cell. |
| `import`, `export` | A file could not be read or written: xlsx, CSV or ods. This includes a missing or wrong [password](https://docs.birchui.com/spreadsheet/encryption.md#errors) and a [cancelled import](https://docs.birchui.com/spreadsheet/xlsx.md#progress-and-cancelling). The rejected promise carries the original error. |
| `readOnly` | A user tried to edit a read-only spreadsheet. |
| `protected` | A user action was blocked by sheet or workbook protection, or a password was wrong. With `enforceProtection: true`, an API call that was blocked. |
| `table` | A table could not be created or changed, for example because it would overlap another table. |
| `dataTable` | A [data table](https://docs.birchui.com/spreadsheet/data-tools.md#data-tables) could not be created, or an edit was refused because the cell holds a data table result. |
| `collaboration` | A [remote operation](https://docs.birchui.com/spreadsheet/collaboration.md#security) was invalid or could not be applied, or undo had nothing left because [remote edits removed the steps](https://docs.birchui.com/spreadsheet/collaboration.md#undo). |

The same messages are announced to screen readers.

## Other exports

| Export | Purpose |
| --- | --- |
| `spreadsheetDefinition` | The widget definition for the [framework adapters](https://docs.birchui.com/spreadsheet/overview.md#use-it-in-your-framework); tag name `birchui-spreadsheet`. |
| `SPREADSHEET_EVENT_NAMES` | The list of event names. |
| `createFormulaEngine(options?)` | The [headless engine](https://docs.birchui.com/spreadsheet/headless-engine.md). |
| `createWorkerEngine(options)`, `exposeFormulaEngine(options?)` | The engine in a [Web Worker](https://docs.birchui.com/spreadsheet/worker-calculation.md). |
| `connectCollaboration(sheet, provider, options)` | Join a [collaboration session](https://docs.birchui.com/spreadsheet/collaboration.md#the-session) through a provider. |
| `createCollaborationAuthority(options?)` | The [server-side function](https://docs.birchui.com/spreadsheet/collaboration.md#the-authority) that orders and transforms operations. No DOM. |
| `createLoopbackProvider(options?)` | An [in-memory authority and transport](https://docs.birchui.com/spreadsheet/collaboration.md#the-loopback-provider) for tests, demos and spreadsheets on one page. |
| `transform(operation, against, order?)`, `transformAll(operations, against, order?)`, `parseOperation(input)` | The [transformation](https://docs.birchui.com/spreadsheet/collaboration.md#what-converges) and the operation validator, for servers and providers of your own. `order` says whether `operation` was ordered `'after'` (the default) or `'before'` `against`. |
| `xlsxToJSON(data, options?)`, `jsonToXlsx(json, options?)` | [xlsx conversion](https://docs.birchui.com/spreadsheet/xlsx.md#without-the-component) without the component. The options include `password`, and for imports `onProgress` and `signal`. |
| `xlsxToJSONWithReport(data, options?)`, `inspectXlsx(data, options?)` | The workbook together with its [import report](https://docs.birchui.com/spreadsheet/xlsx.md#import-report), or the report alone. |
| `validateXlsxPackage(bytes, options?)` | [Check an xlsx file](https://docs.birchui.com/spreadsheet/xlsx.md#checking-a-file) for structural mistakes. |
| `renderMetafile(bytes)` | Converts an EMF or WMF picture to SVG, as the grid does for [Windows metafiles](https://docs.birchui.com/spreadsheet/images.md#windows-metafiles). |
| `detectEmbeddedFileType(bytes, hints?)` | The [type of a file](https://docs.birchui.com/spreadsheet/embedded-objects.md#file-types) from its bytes and optional hints (`progId`, `fileName`, `contentType`, `partName`), as `{ kind, label, badge, extension, mime }`. No DOM; it never throws. |
| `canvasImageRasterizer` | The rasterizer the browser export uses for [SVG and WebP pictures](https://docs.birchui.com/spreadsheet/xlsx.md#svg-and-webp-pictures). |
| `isEncryptedPackage(bytes)`, `describeEncryption(bytes)` from `@birchui/spreadsheet/encryption` | Whether a file is [password-protected](https://docs.birchui.com/spreadsheet/encryption.md#asking-for-the-password), and with which cipher, key size, hash and iteration count. |
| `csvToJSON(data, options?)`, `jsonToCsv(json, options?)` | [CSV and TSV conversion](https://docs.birchui.com/spreadsheet/file-formats.md#csv-and-tsv). |
| `detectCsvDialect(text)`, `readCsvDialect(data, encoding?)`, `parseCsv(text, options?)` | The detected delimiter, quote, line ending and encoding of delimited text, and the parser alone. See [What is detected](https://docs.birchui.com/spreadsheet/file-formats.md#what-is-detected). |
| `odsToJSON(data, options?)`, `jsonToOds(json, options?)` | [OpenDocument conversion](https://docs.birchui.com/spreadsheet/file-formats.md#opendocument-spreadsheets). |
| `xlsToJSON(data, options?)`, `xlsToJSONWithReport(data, options?)`, `isXlsWorkbook(bytes)`, `XlsError`, `DEFAULT_XLS_LIMITS` | Read [legacy `.xls` files](https://docs.birchui.com/spreadsheet/file-formats.md#legacy-xls-files) of Excel 97-2003. Synchronous, no DOM. There is no `.xls` export. |
| `jsonToPdf(json, options?)` | [PDF export](https://docs.birchui.com/spreadsheet/printing.md#export-to-pdf) without the component or a DOM. |
| `jsonToXlsxWithReport(json, options?)` | The xlsx bytes together with a report of what the exporter [adjusted](https://docs.birchui.com/spreadsheet/xlsx.md#table-header-cells-and-column-names). |
| `sanitizeWorkbook(json)`, `safeColor(value)`, `safeFontFamily(value)`, `safeLinkUrl(value)`, `safeImageSource(value)` | The checks applied to [untrusted workbooks](https://docs.birchui.com/spreadsheet/security.md). |
| `DataTableError` | Thrown by `addDataTable()` for a definition that cannot work. See [Data tables](https://docs.birchui.com/spreadsheet/data-tools.md#data-tables). |
| `ZipLimitError`, `DEFAULT_ZIP_LIMITS` | The error and the defaults of the [zip limits](https://docs.birchui.com/spreadsheet/security.md#zip-limits) on xlsx and ods import. |
| `formulaToLocale(formula, locale)`, `formulaFromLocale(text, locale)`, `inputFromLocale(text, locale)`, `resolveFormatLocale(tag)`, `DE_DE`, `FR_FR`, `ES_ES`, `EN_US` | [Locale](https://docs.birchui.com/spreadsheet/formatting.md#locales) conversion for formulas and typed input, and the built-in locale objects. |
| `toOpenFormula(formula)`, `fromOpenFormula(formula)` from `@birchui/spreadsheet/ods` | Convert a formula between Excel syntax and [OpenFormula](https://docs.birchui.com/spreadsheet/file-formats.md#formula-conversion). |
| `listFunctions()` | Every built-in function as `{ name, category, args, summary, volatile }`, sorted by name. The [function reference](https://docs.birchui.com/spreadsheet/functions.md) is generated from it. |
| `formatValue(value, code)`, `formatKind(code)`, `isDateFormat(code)` | The [number formatter](https://docs.birchui.com/spreadsheet/formatting.md#number-formats). |
| `dateToSerial(date)`, `serialToDate(serial)` | Convert between `Date` objects and date serials, in UTC. |
| `formulaToR1C1(formula, cell)`, `formulaFromR1C1(formula, cell)` | Convert a formula between A1 and [R1C1 notation](https://docs.birchui.com/spreadsheet/formulas.md#r1c1-notation), relative to the cell that holds it. |
| `toA1(row, column)`, `fromA1(address)`, `columnName(column)` | Convert between 0-based indexes and A1 addresses: `toA1(0, 27)` is `AB1`, `fromA1('AB12')` is `{ row: 11, col: 27 }`. |
| `isCellError(value)` | Whether a cell value is an error, such as `#N/A`. |
| `ValidationError`, `ProtectionError` | The errors thrown by blocked API writes. `ValidationError` has `sheet`, `address` (the first rejected cell) and `rejected` (how many cells failed); `ProtectionError` has `sheet` for a protected sheet and no `sheet` for the workbook structure. |
| `spreadsheetStyles` | The component's CSS as a string. |

Types include `WorkbookJSON`, `SheetJSON`, `CellJSON`, `CellStyle`, `CellValue`, `CellInput`, `ConditionalFormat` and its rule types, `DataValidation`, `TableJSON`, `CellNote`, `Hyperlink`, `SheetProtection`, `ImageJSON`, `ChartJSON` with `ChartSeries`, `ChartTrendline`, `ChartErrorBars`, `ChartDataLabels` and `ChartAxisOptions`, `SparklineGroup`, `PageSetup`, `FindOptions`, `WriteOptions`, `ValidationMode`, `SheetOperation`, `SheetOperationEvent`, `PresenceCursor`, `CollaborationProvider`, `CollaborationSession`, `CollaborationOptions`, `CollaborationAuthority`, `CommittedOperation`, `ClientMessage`, `ServerMessage`, `FormulaEngine`, `FunctionInfo`, `CustomFunctionSet`, `CustomFunctionDefinition`, `CustomFunctionOptions` and `CustomFunctionImpl`. For files there are `XlsxExportOptions`, `XlsxOpenOptions`, `XlsxImportOptions`, `XlsxImportProgress`, `XlsxImportPhase`, `XlsxImportReport`, `XlsxReportEntry`, `XlsxValidationIssue`, `CsvImportOptions`, `CsvExportOptions`, `CsvDialect`, `CsvParseResult`, `OdsImportOptions`, `OdsExportOptions`, `EncryptionError`, `EncryptionErrorCode` and `EncryptionSummary`; for the model, `PivotTableJSON`, `SlicerJSON`, `ShapeJSON`, `SheetView`, `DocumentProperties`, `SortState` and `ColumnFilter`.
