Initialize Sheetwrite, create a workbook, and observe committed changes.On this page
Loading documentation…
This complete TypeScript example uses the imperative core. Install Sheetwrite first; the framework adapters expose the same Grid after their client-only initialization completes.
initSheetwrite() is re-entrant. Call it before createGrid; concurrent calls share initialization and a failed call can be retried. Destroy the returned grid when its host is permanently removed.
Add a formula
A formula is a cell value with kind: "formula". The engine calculates it at once, and dependent cells follow every later edit.
Users can type the same formula in the cell. To use GROUPBY, LAMBDA, regression, and the other analysis functions, select the full formula engine before you create the grid.
Save and open the document
exportSnapshot() returns the complete document: values, formulas, styles, and sheet settings. Store it as JSON, and open it later with createGridFromSnapshot. Selection, scroll position, and zoom are session state; they are not in the snapshot.
function createGrid(host: HTMLElement, opts: GridOptions): GridfunctioncreateGrid(host:HTMLElement,opts:GridOptions,):GridfunctioncreateGrid(host:HTMLElement,opts:GridOptions,):GridCreates and mounts an imperative Grid in the supplied host element.@example import { createGrid, initSheetwrite } from "@sheetwrite/core"; await initSheetwrite(); const host = document.createElement("div"); host.style.height = "400px"; document.body.append(host); const grid = createGrid(host, { workbook: { activeSheet: "sales", sheets: [{ id: "sales", name: "Sales", rowCount: 2, columns: [{ key: "amount", header: "Amount", type: "number", width: 120 }] }], }, data: { rowCount: 2, columns: { amount: [12, 18] } }, }); grid.scrollToCell({ sheet: "sales", row: 1, col: 0 }); // Call when the host view is removed. grid.destroy();@see Grid *@see GridOptionsAPI reference →function initSheetwrite(source?: BufferSource | URL | string | Request | WebAssembly.Module, engine?: SheetwriteEngine): Promise<void>functioninitSheetwrite(source?:BufferSource|URL|string|Request|WebAssembly.Module,engine?:SheetwriteEngine,):Promise<void>functioninitSheetwrite(source?:|BufferSource|URL|string|Request|WebAssembly.Module,engine?:SheetwriteEngine,):Promise<void>Load one WASM engine before createGrid. The default is @sheetwrite/wasm. Pass the @sheetwrite/formulas module as the second argument to select the full engine.@example import { initSheetwrite } from "@sheetwrite/core"; import * as formulas from "@sheetwrite/formulas"; await initSheetwrite(undefined, formulas);@see /docs/guides/formulas/@see createGridAPI reference →interface ColumnarDatainterfaceColumnarDatainterfaceColumnarDataEager column-oriented values used to initialize a sheet.API reference →interface WorkbookinterfaceWorkbookinterfaceWorkbookLive workbook schema containing ordered sheets and the active sheet ID.API reference →const host: HTMLElement | nullconsthost:HTMLElement|nullconsthost:HTMLElement|nullvar document: Documentvar document:Documentvar document:Documentwindow.document returns a reference to the document contained in the window. MDN ReferenceParentNode.querySelector<HTMLElement>(selectors: string): HTMLElement | null (+4 overloads)ParentNode.querySelector<HTMLElement>(selectors: string): HTMLElement |null (+4 overloads)ParentNode.querySelector<HTMLElement>(selectors: string): HTMLElement |null (+4 overloads)Returns the first element that is a descendant of node that matches selectors. MDN Referenceinterface HTMLElementinterfaceHTMLElementinterfaceHTMLElementThe HTMLElement interface represents any HTML element. MDN Referencevar Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+2 overloads)var Error:ErrorConstructornew (message?:string, options?:ErrorOptions) =>Error (+2 overloads)var Error:ErrorConstructornew (message?:string, options?:ErrorOptions) =>Error (+2 overloads)const host: HTMLElementconsthost:HTMLElementconsthost:HTMLElementElementCSSInlineStyle.style: CSSStyleDeclarationinterfaceElementCSSInlineStyle {style:CSSStyleDeclaration;}interfaceElementCSSInlineStyle {style:CSSStyleDeclaration;}MDN ReferenceAPI reference →CSSStyleDeclaration.height: stringinterfaceCSSStyleDeclaration {height:string;}interfaceCSSStyleDeclaration {height:string;}MDN ReferenceAPI reference →const workbook: Workbookconstworkbook:Workbookconstworkbook:WorkbookLive workbook schema adopted by the store and updated by document operations.API reference →Workbook.activeSheet: stringinterfaceWorkbook {activeSheet:string;}interfaceWorkbook {activeSheet:string;}Active sheet ID and initial tab presented when the grid is created.API reference →Workbook.sheets: Sheet[]interfaceWorkbook {sheets:Sheet[];}interfaceWorkbook {sheets:Sheet[];}Sheets in display/tab order.API reference →Sheet.id: stringinterfaceSheet {id:string;}interfaceSheet {id:string;}Stable identifier, unique within the workbook and used by every cell address.API reference →Sheet.name: stringinterfaceSheet {name:string;}interfaceSheet {name:string;}User-facing sheet name shown in tabs and workbook exports.API reference →Sheet.rowCount: numberinterfaceSheet {rowCount:number;}interfaceSheet {rowCount:number;}Row count for both in-memory and datasource-backed sheets.API reference →Sheet.columns: Column[]interfaceSheet {columns:Column[];}interfaceSheet {columns:Column[];}Ordered schema; array positions are the zero-based column coordinates.API reference →Column.key: stringinterfaceColumn {key:string;}interfaceColumn {key:string;}Non-empty key, unique within the sheet, used to map input and datasource values.API reference →Column.header: stringinterfaceColumn {header:string;}interfaceColumn {header:string;}Schema label used by table exports and data-grid presentation headers.API reference →Column.width: numberinterfaceColumn {width:number;}interfaceColumn {width:number;}Unzoomed column width in CSS pixels.API reference →Column.type: CellFormatinterfaceColumn {type:CellFormat;}interfaceColumn {type:CellFormat;}Controls cell input parsing and default value formatting for this column.API reference →const data: ColumnarDataconstdata:ColumnarDataconstdata:ColumnarDataEager column-major values loaded into workbook.activeSheet; use instead of datasource.API reference →ColumnarData.rowCount: numberinterfaceColumnarData {rowCount:number;}interfaceColumnarData {rowCount:number;}Row count for both in-memory and datasource-backed sheets.API reference →ColumnarData.columns: Record<string, ArrayLike<CellScalar | CellValue>>interfaceColumnarData {columns:Record<string, ArrayLike<CellScalar|CellValue>>;}interfaceColumnarData {columns:Record<string,ArrayLike<CellScalar|CellValue>>;}Exact column runs represented by every returned row.API reference →product: string[]let product:string[]let product:string[]amount: Float64Array<ArrayBuffer>let amount:Float64Array<ArrayBuffer>let amount:Float64Array<ArrayBuffer>var Float64Array: Float64ArrayConstructor
new (elements: Iterable<number>) => Float64Array<ArrayBuffer> (+6 overloads)var Float64Array:Float64ArrayConstructornew (elements:Iterable<number>) =>Float64Array<ArrayBuffer> (+6 overloads)var Float64Array:Float64ArrayConstructornew (elements:Iterable<number>) =>Float64Array<ArrayBuffer> (+6 overloads)const grid: Gridconstgrid:Gridconstgrid:GridThe imperative core grid this controller owns.API reference →GridOptions.workbook: WorkbookinterfaceGridOptions {workbook:Workbook;}interfaceGridOptions {workbook:Workbook;}Live workbook schema adopted by the store and updated by document operations.API reference →GridOptions.data?: ColumnarData | undefinedinterfaceGridOptions {data?:ColumnarData|undefined;}interfaceGridOptions {data?:ColumnarData|undefined;}Eager column-major values loaded into workbook.activeSheet; use instead of datasource.API reference →Grid.on<"change">(evt: "change", fn: (e: ChangeEvent) => void): () => voidGrid.on<"change">(evt: "change", fn: (e:ChangeEvent) =>void): () =>voidGrid.on<"change">(evt: "change", fn: (e:ChangeEvent) =>void): () =>voidtransaction: Transactionlet transaction:Transactionlet transaction:TransactionOperations that actually committed after policy and bounds filtering.API reference →var console: Consolevar console:Consolevar console:ConsoleConsole.log(...data: any[]): void (+1 overload)Console.log(...data: any[]): void (+1 overload)Console.log(...data: any[]): void (+1 overload)The console.log() static method outputs a message to the console. MDN ReferenceTransaction.patches: DocumentOp[]interfaceTransaction {patches:DocumentOp[];}interfaceTransaction {patches:DocumentOp[];}Ordered document operations submitted as one store commit.API reference →Grid.applyTransaction(transaction: GridTransaction): ApplyTransactionResultGrid.applyTransaction(transaction: GridTransaction): ApplyTransactionResultGrid.applyTransaction(transaction: GridTransaction): ApplyTransactionResultApply arbitrary patches as one undoable Grid commit. No-op when read-only. Use Store.applyTransaction only for low-level writes that intentionally bypass Grid history and policy.@example import type { Grid } from "@sheetwrite/core"; function setFirstCell(grid: Grid) { return grid.applyTransaction({ patches: [ { op: "set", addr: { sheet: grid.getActiveSheet(), row: 0, col: 0 }, value: { kind: "literal", value: 42 } }, ] }); }@see TransactionAPI reference →GridTransaction.patches: DocumentOp[]interfaceGridTransaction {patches:DocumentOp[];}interfaceGridTransaction {patches:DocumentOp[];}Ordered document operations submitted as one store commit.API reference →addr: CellAddresslet addr:CellAddresslet addr:CellAddressAPI reference →CellAddress.sheet: stringinterfaceCellAddress {sheet:string;}interfaceCellAddress {sheet:string;}Sheet identity used by the simple data-first adapter. Defaults to sheet1.API reference →CellAddress.row: numberinterfaceCellAddress {row:number;}interfaceCellAddress {row:number;}API reference →CellAddress.col: numberinterfaceCellAddress {col:number;}interfaceCellAddress {col:number;}API reference →value: CellValuelet value:CellValuelet value:CellValueAPI reference →src: stringlet src:stringlet src:stringGrid.store: StoreinterfaceGrid {store:Store;}interfaceGrid {store:Store;}Store.getCell(addr: CellAddress): ResolvedCellStore.getCell(addr: CellAddress): ResolvedCellStore.getCell(addr: CellAddress): ResolvedCellSingle-cell read for interactions, API reads, and tests. NOT for the render hot path — renderers use getVisibleWindow.API reference →ResolvedCell.resolved: CellScalarinterfaceResolvedCell {resolved:CellScalar;}interfaceResolvedCell {resolved:CellScalar;}const saved: stringconstsaved:stringconstsaved:stringvar JSON: JSONvarJSON:JSONvarJSON:JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.JSON.stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string (+1 overload)JSON.stringify(value: any, replacer?: (this:any, key:string, value:any) => any, space?: string | number): string (+1 overload)JSON.stringify(value: any, replacer?: (this:any, key:string, value:any) => any, space?: string | number): string (+1 overload)Converts a JavaScript value to a JavaScript Object Notation (JSON) string.@param value A JavaScript value, usually an object or array, to be converted.@param replacer A function that transforms the results.@param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.@throws {TypeError} If a circular reference or a BigInt value is found.Grid.exportSnapshot(): WorkbookSnapshotGrid.exportSnapshot(): WorkbookSnapshotGrid.exportSnapshot(): WorkbookSnapshotDeterministically export the complete authoritative workbook document.API reference →Grid.destroy(): voidGrid.destroy(): voidGrid.destroy(): voidRuns immediately before a retained element is removed or replaced.API reference →const reopened: Gridconstreopened:Gridconstreopened:GridAPI reference →function createGridFromSnapshot(host: HTMLElement, snapshot: unknown, options?: SnapshotGridOptions): GridfunctioncreateGridFromSnapshot(host:HTMLElement,snapshot:unknown,options?:SnapshotGridOptions,):GridfunctioncreateGridFromSnapshot(host:HTMLElement,snapshot:unknown,options?:SnapshotGridOptions,):GridMount a grid over a validated, non-dirty snapshot. The grid owns and disposes the hydrated store just like one created through createGrid.API reference →JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): anyJSON.parse(text: string, reviver?: (this:any, key:string, value:any) => any): anyJSON.parse(text: string, reviver?: (this:any, key:string, value:any) => any): anyConverts a JavaScript Object Notation (JSON) string into an object.@param text A valid JSON string.@param reviver A function that transforms the results. This function is called for each member of the object. If a member contains nested objects, the nested objects are transformed before the parent object is.@throws {SyntaxError} If text is not valid JSON.