Skip to content

Grid methods

The imperative Grid handle that createGrid returns, grouped by task: document and sheets, selection and editing, views, layout and lifecycle.
On this page

createGrid returns an imperative Grid handle. Use it to read and change the document, the selection, the view and the layout.

Drive the grid from code
grid.setSelection({ kind: "cell", addr: { sheet, row: 0, col: 1 } });
grid.sortBy(1, false); // display-only sort, largest first
grid.setFrozen(1); // pin the first view row
grid.setZoom(1.25);
console.log(grid.getZoom()); // 1.25
const off = grid.on("selection", ({ selection }) => console.log(selection));
// later
off();
AB
1Desk300
2Chair120
3Lamp40
Result: costs are displayed largest first, with Desk at the top. The first view row is frozen and the live grid is zoomed to 125%.
Usage example (requires an initialized grid)

This API excerpt needs an initialized grid with a text item column and a numeric cost column. Use these data rows in order: Lamp / 40, Desk / 300, Chair / 120. There is no header row in the cell data.

Drive the grid from code
grid.setSelection({ kind: "cell", addr: { sheet, row: 0, col: 1 } });
grid.sortBy(1, false); // display-only sort, largest first
grid.setFrozen(1); // pin the first view row
grid.setZoom(1.25);
console.log(grid.getZoom()); // 1.25
const off = grid.on("selection", ({ selection }) => console.log(selection));
// later
off();

The grid shows column B sorted from largest to smallest, the first row stays in place while the body scrolls, and content is drawn at 125%.

Each name in the tables links to its entry in the Grid API reference. These are the signatures of the methods on this page:

Grid signatures
interface Grid {
readonly store: Store;
readonly actions: GridActions;
setActiveSheet(id: SheetId): void;
scrollToCell(addr: CellAddress): void;
getSelection(): Selection | null;
setSelection(sel: Selection | null): void;
setTheme(theme: Partial<Theme>): void;
defineCellRenderer(name: string, renderer: CellRenderer): void;
aggregate(col: number, op: AggregateOp): number;
sortBy(col: number, ascending?: boolean): void;
sortByMulti(keys: readonly SortKey[]): void;
filterBy(col: number, needle: string): void;
setColumnFilter(col: number, filter: ColumnFilter | null): void;
getColumnFilters(): ReadonlyMap<number, ColumnFilter>;
distinctValues(col: number, limit?: number): CellScalar[];
hideRows(rows: readonly number[]): void;
showRows(rows?: readonly number[]): void;
hiddenRows(): readonly number[];
hideColumns(cols?: readonly number[]): void;
showColumns(cols?: readonly number[]): void;
hiddenColumns(): readonly number[];
groupRows(start: number, end: number): void;
ungroupRows(start: number, end: number): void;
setGroupCollapsed(start: number, collapsed: boolean): void;
rowGroups(): readonly RowGroup[];
clearView(): void;
undo(): void;
redo(): void;
exportCsv(filename: string): void;
exportXlsx(filename: string): Promise<void>;
clearSearch(): void;
replaceCurrent(replacement: string): SearchResult;
replaceAll(replacement: string): ReplaceResult;
insertRows(at: number, count?: number): void;
removeRows(at: number, count?: number): void;
insertColumns(at: number, count?: number): void;
removeColumns(at: number, count?: number): void;
highlightCells(ranges: readonly HighlightRange[] | null, color?: string): void;
styleRange(range: Range, style: Partial<CellStyle> | null): void;
setValidationRule(rule: DataValidationRule): ApplyTransactionResult;
removeValidationRule(id: string): ApplyTransactionResult;
removeProtectedRange(id: string): ApplyTransactionResult;
setNote(addr: CellAddress, text: string | null): ApplyTransactionResult;
getNote(addr: CellAddress): string | null;
beginEdit(row: number, col: number, initial?: string, selectAll?: boolean): void;
dataEdge(row: number, col: number, dRow: number, dCol: number): number | null;
setRowHeight(row: number, height: number): void;
setColumnWidth(col: number, width: number): void;
autoFitColumns(cols?: readonly number[]): void;
setFrozen(rows: number, cols?: number): void;
setZoom(zoom: number): void;
getZoom(): number;
on<E extends keyof GridEvents>(evt: E, fn: (e: GridEvents[E]) => void): () => void;
refresh(): void;
destroy(): void;
// Also covered under "Other methods" below:
getCellAtPoint(clientX: number, clientY: number): CellAddress | null;
setConfig(config: GridConfig | undefined): void;
setReadOnly(readOnly: boolean): void;
}

Document and sheets

MethodPurpose
storeThe underlying Store: apply transactions, read cells, subscribe.
actionsImperative action surface (toggleBold(), merge(), undo(), exportCsv(), …) the toolbar and context menu bind to. Use it to wire custom controls.
setActiveSheet(id)Switch the visible sheet.
undo() / redo()Undo or redo the last recorded cell edit (also bound to Ctrl+Z / Ctrl+Shift+Z).
insertRows(at, count?) / removeRows(at, count?) / insertColumns(at, count?) / removeColumns(at, count?)Structural edits through undoable patches.
styleRange(range, style)Merge or clear (null) store-backed cell styles across a range.
setValidationRule(rule) / removeValidationRule(id)Add, replace, or remove a serializable range validation rule. List and checkbox rules get accessible editors.
setProtectedRange(range) / removeProtectedRange(id) / setProtectionResolver(resolver?, mode?)Define protected-range metadata and host-owned local permission policy. This is not server authorization.
setNote(addr, text) / getNote(addr)Set, clear (null), or read a serializable plain-text cell note.
exportCsv(filename) / exportXlsx(filename)Download the active data; exportXlsx returns a promise. See Data operations.
MethodPurpose
getSelection() / setSelection(sel)Read or set the current Selection (null clears it).
scrollToCell(addr)Scroll a cell into view.
beginEdit(row, col, initial?, selectAll?)Open the inline editor at a view cell.
dataEdge(row, col, dRow, dCol)Ctrl+Arrow-style data-run jump target, or null; vertical movement is view-aware under sort/filter.
search(query, opts?)Find matching cells; highlights them, emits search, returns a SearchResult.
findNext() / findPrev()Step the active match forward / backward and scroll it into view.
clearSearch()Drop the current search and clear its highlights.
replaceCurrent(replacement) / replaceAll(replacement)Replace literal text/number matches through undoable transactions.
highlightCells(ranges, color?)Highlight arbitrary ranges (null clears); color overrides the theme highlight.

Views: sort, filter, hide and group

MethodPurpose
aggregate(col, op)Column aggregate (returns a number); see Data operations.
sortBy(col, ascending?) / sortByMulti(keys)Non-mutating display sorts; see Data operations.
filterBy(col, needle) / setColumnFilter(col, filter) / getColumnFilters()Column filters that compose with sort, hidden rows, and row groups. setColumnFilter(col, null) removes one.
distinctValues(col, limit?)First-seen distinct values for building filter menus.
hideRows(rows) / showRows(rows?) / hiddenRows()Explicit row visibility separate from sort/filter state.
hideColumns(cols?) / showColumns(cols?) / hiddenColumns()Bulk-safe persisted column visibility; omitted arguments target the focused column for hide and every column for show.
groupRows(start, end) / ungroupRows(start, end) / setGroupCollapsed(start, collapsed) / rowGroups()Inclusive data-row groups with collapse state.
clearView()Clears sort/filter state; hidden rows and row groups remain.

Layout and appearance

MethodPurpose
setFrozen(rows, cols?)Pin leading view rows/columns while the body scrolls.
setZoom(z) / getZoom()Scale grid content between 0.5 and 2 without mutating workbook base sizes.
setRowHeight(row, h) / setColumnWidth(col, w)Geometry APIs; row height is view-indexed and persists against the underlying data row.
autoFitRows(range?) / autoFitColumns(cols?)Explicit, undoable geometry fitting from bulk reads; auto-fit never runs during paint.
setTheme(partial)Merge a partial theme and repaint.
defineCellRenderer(name, r)Register a custom renderer after construction. See Custom cell renderers.

Lifecycle

MethodPurpose
on(evt, fn)Subscribe to an event; returns an unsubscribe function.
refresh()Force a re-render, for example after mutating the workbook directly.
destroy()Tear down listeners, DOM, and ARIA attributes.

Other methods

MethodPurpose
applyTransaction(transaction)Apply arbitrary patches as one undoable grid commit.
exportSnapshot() / applyRemoteOperations(operations)Export the complete document, or apply already-persisted operations. See Persistence.
getCommandState(name)Undo/redo availability and formatting active/mixed/disabled state. See Host-owned command state.
getFocusCellStyle()Effective style of the focus cell: its own style over its column's cellStyle.
getCellAtPoint(clientX, clientY)Resolve viewport coordinates to an active-sheet cell for host-owned menus.
setConfig(config) / setReadOnly(readOnly)Reconfigure built-in chrome, or change editability, without replacing the grid.

Edge cases and limits

  • Undo history keeps at most 200 entries. It also drops its oldest entries once retained range snapshots pass 256 MiB, about twenty million-cell clears. The newest entry always stays undoable.
  • The 256 MiB policy counts engine-reported snapshot bytes, not total process memory. Cloned formula ASTs and JavaScript patch/redo payloads are bounded only by the 200-entry limit.
  • Undo of a large clear restores the saved range directly from a packed engine snapshot.
  • Display sorts and filters do not change the document. clearView() keeps hidden rows and row groups.

See also

Documentation