console . log ( total ); // 195 for Ada: 120 and Lin: 75
Descending Total: stored row data stays in its original order
Try it live: sort and filter orders .
Full setup
import "@sheetwrite/core/styles.css" ;
const host = document . querySelector < HTMLElement >( "#grid" ); if ( ! host ) throw new Error ( "Missing #grid host" );
customer : [ "Lin" , "Ada" ], total : new Float64Array ([ 75 , 120 ]),
Sheetwrite can sort, filter, hide, group, aggregate, import, and export the active
sheet without rewriting the stored row data. Sorts and filters are display views:
the store keeps a row-order permutation/subset and the renderer reads through it.
Display views
The simple shorthands are still available:
grid . filterBy ( 3 , "Tokyo" ); // keep rows whose column-3 text contains "Tokyo"
For custom UI, use the composable primitives. All active column filters are ANDed
together, hidden rows and collapsed groups are subtracted, and the remaining rows
are sorted by the active multi-key sort.
Method Signature Effect sortBysortBy(col: number, ascending = true): voidReorder displayed rows by one column. sortByMultisortByMulti(keys: readonly SortKey[]): voidStable multi-key sort; first key is primary. filterByfilterBy(col: number, needle: string): voidShorthand for a case-insensitive contains column filter. setColumnFiltersetColumnFilter(col: number, filter: ColumnFilter | null): voidSet or clear one column filter. getColumnFiltersgetColumnFilters(): ReadonlyMap<number, ColumnFilter>Current active column filters. distinctValuesdistinctValues(col: number, limit = 1000): CellScalar[]First-seen distinct resolved values for a column. hideRows / showRowshideRows(rows) / showRows(rows?)Hide/show data rows independent of sort/filter state. hiddenRowshiddenRows(): readonly number[]Currently hidden data rows. groupRows / ungroupRowsgroupRows(start, end) / ungroupRows(start, end)Create/remove an inclusive data-row group. setGroupCollapsedsetGroupCollapsed(start, collapsed): voidCollapse or expand the group starting at start. rowGroupsrowGroups(): readonly RowGroup[]Current row-group definitions. clearViewclearView(): voidClears sort/filter state. Hidden rows and row groups are preserved.
clearView() deliberately does not unhide rows or expand row groups. This
matches spreadsheet behavior: clearing a filter removes the query, but explicit
hidden rows and collapsed groups remain a separate visibility state. Use
showRows() and setGroupCollapsed(start, false) to reverse those states.
Because a view reorders or hides rows, two features that depend on a stable
row-to-cell mapping are disabled while a view is active:
Merged cells are not drawn (the layout reports no merges under a view).
Drag-to-fill is unavailable (the fill handle is hidden).
Call clearView() to remove sort/filter state; also show hidden rows / expand
row groups if you need the full natural data order.
Aggregate
aggregate computes a column reduction over the active sheet's data and returns a
number:
Frozen panes and zoom
Frozen panes and zoom are view geometry, not data mutations:
setFrozen(rows, cols?) pins leading view rows and columns while the body
scrolls. setZoom(z) clamps to 0.5-2 and scales painted row/column geometry
and fonts; workbook widths/heights remain in base units.
See also
Interaction for clipboard TSV and the toolbar sort control.
Concepts for row/column DocumentOp transactions.
const grid: Grid const grid : Grid const grid : Grid The imperative core grid this controller owns. API reference → Grid.sortBy(col: number, ascending?: boolean): void Grid. sortBy (col: number, ascending ?: boolean): void Grid. sortBy (col: number, ascending ?: boolean): void Sort the displayed rows by a column (does not mutate stored data). Example import type { Grid } from "@sheetwrite/core" ;
function showLargestFirst ( grid : Grid ) {
grid. sortBy ( 1 , false );
} See also Grid.clearView API reference → const total: number const total : number const total : number Grid.aggregate(col: number, op: AggregateOp): number Grid. aggregate (col: number, op: AggregateOp): number Grid. aggregate (col: number, op: AggregateOp): number Column aggregate over the active sheet's data. Example import type { Grid } from "@sheetwrite/core" ;
function total ( grid : Grid ) {
return grid. aggregate ( 1 , "sum" );
} See also SheetwriteStore.aggregate API reference → var console: Console var console : Console var console : Console Console.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 Reference function createGrid(host: HTMLElement, opts: GridOptions): Grid function createGrid (
host : HTMLElement ,
opts : GridOptions ,
) : Grid function createGrid (
host : HTMLElement ,
opts : GridOptions ,
) : Grid Creates 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 also Grid * See also GridOptions API reference → function initSheetwrite(source?: BufferSource | URL | string | Request | WebAssembly.Module, engine?: SheetwriteEngine): Promise<void> function initSheetwrite (
source ?:
BufferSource | URL | string | Request | WebAssembly . Module ,
engine ?: SheetwriteEngine ,
) : Promise < void > function initSheetwrite (
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 also /docs/start/choose-an-engine/ See also createGrid API reference → interface Workbook interface Workbook interface Workbook Live workbook schema containing ordered sheets and the active sheet ID. API reference → const host: HTMLElement | null const host : HTMLElement | null const host : HTMLElement | null var document: Document var document : Document var document : Document window.document returns a reference to the document contained in the window. MDN Reference API reference → ParentNode.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 Reference interface HTMLElement interface HTMLElement interface HTMLElement The HTMLElement interface represents any HTML element. MDN Reference var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+2 overloads) var Error : ErrorConstructor
new ( message ?: string , options ?: ErrorOptions ) => Error ( + 2 overloads) var Error : ErrorConstructor
new ( message ?: string , options ?: ErrorOptions ) => Error ( + 2 overloads) const host: HTMLElement const host : HTMLElement const host : HTMLElement ElementCSSInlineStyle.style: CSSStyleDeclaration interface ElementCSSInlineStyle {
style : CSSStyleDeclaration ;
} interface ElementCSSInlineStyle {
style : CSSStyleDeclaration ;
} MDN Reference API reference → CSSStyleDeclaration.height: string interface CSSStyleDeclaration {
height : string ;
} interface CSSStyleDeclaration {
height : string ;
} MDN Reference API reference → const workbook: Workbook const workbook : Workbook const workbook : Workbook Live workbook schema adopted by the store and updated by document operations. API reference → Workbook.activeSheet: string interface Workbook {
activeSheet : string ;
} interface Workbook {
activeSheet : string ;
} Active sheet ID and initial tab presented when the grid is created. API reference → Workbook.sheets: Sheet[] interface Workbook {
sheets : Sheet [];
} interface Workbook {
sheets : Sheet [];
} Sheets in display/tab order. API reference → Sheet.id: string interface Sheet {
id : string ;
} interface Sheet {
id : string ;
} Stable identifier, unique within the workbook and used by every cell address. API reference → Sheet.name: string interface Sheet {
name : string ;
} interface Sheet {
name : string ;
} User-facing sheet name shown in tabs and workbook exports. API reference → Sheet.rowCount: number interface Sheet {
rowCount : number ;
} interface Sheet {
rowCount : number ;
} Row count for both in-memory and datasource-backed sheets. API reference → Sheet.columns: Column[] interface Sheet {
columns : Column [];
} interface Sheet {
columns : Column [];
} Ordered schema; array positions are the zero-based column coordinates. API reference → Column.key: string interface Column {
key : string ;
} interface Column {
key : string ;
} Non-empty key, unique within the sheet, used to map input and datasource values. API reference → Column.header: string interface Column {
header : string ;
} interface Column {
header : string ;
} Schema label used by table exports and data-grid presentation headers. API reference → Column.width: number interface Column {
width : number ;
} interface Column {
width : number ;
} Unzoomed column width in CSS pixels. API reference → Column.type: CellFormat interface Column {
type : CellFormat ;
} interface Column {
type : CellFormat ;
} Controls cell input parsing and default value formatting for this column. API reference → GridOptions.workbook: Workbook interface GridOptions {
workbook : Workbook ;
} interface GridOptions {
workbook : Workbook ;
} Live workbook schema adopted by the store and updated by document operations. API reference → GridOptions.data?: ColumnarData | undefined interface GridOptions {
data ?: ColumnarData | undefined ;
} interface GridOptions {
data ?: ColumnarData | undefined ;
} Eager column-major values loaded into workbook.activeSheet; use instead of datasource. API reference → ColumnarData.rowCount: number interface ColumnarData {
rowCount : number ;
} interface ColumnarData {
rowCount : number ;
} Row count for both in-memory and datasource-backed sheets. API reference → ColumnarData.columns: Record<string, ArrayLike<CellScalar | CellValue>> interface ColumnarData {
columns : Record < string , ArrayLike < CellScalar | CellValue >>;
} interface ColumnarData {
columns : Record <
string ,
ArrayLike <
CellScalar | CellValue
>
>;
} Exact column runs represented by every returned row. API reference → customer: string[] let customer : string [] let customer : string [] total: Float64Array<ArrayBuffer> let total : Float64Array < ArrayBuffer > let total : Float64Array < ArrayBuffer > var Float64Array: Float64ArrayConstructor
new (elements: Iterable<number>) => Float64Array<ArrayBuffer> (+6 overloads) var Float64Array : Float64ArrayConstructor
new ( elements : Iterable < number >) => Float64Array < ArrayBuffer > ( + 6 overloads) var Float64Array : Float64ArrayConstructor
new ( elements : Iterable < number >) => Float64Array < ArrayBuffer > ( + 6 overloads) Grid.filterBy(col: number, needle: string): void Grid. filterBy (col: number, needle: string): void Grid. filterBy (col: number, needle: string): void Filter the displayed rows to those whose column text contains needle. Example import type { Grid } from "@sheetwrite/core" ;
function showOpenRows ( grid : Grid ) {
grid. filterBy ( 0 , "Open" );
} See also Grid.clearView API reference → Grid.clearView(): void Grid. clearView (): void Grid. clearView (): void Clear any active sort/filter view. API reference → Grid.sortByMulti(keys: readonly SortKey[]): void Grid. sortByMulti (keys: readonly SortKey[]): void Grid. sortByMulti (keys: readonly SortKey[]): void Multi-key sort of the displayed rows (first key primary; stable). API reference → SortKey.col: number interface SortKey {
col : number ;
} interface SortKey {
col : number ;
} 0-based column of the cell that holds the top-left corner. API reference → SortKey.ascending: boolean interface SortKey {
ascending : boolean ;
} interface SortKey {
ascending : boolean ;
} API reference → Grid.setColumnFilter(col: number, filter: ColumnFilter | null): void Grid. setColumnFilter (col: number, filter: ColumnFilter | null ): void Grid. setColumnFilter (col: number, filter: ColumnFilter | null ): void Set or clear (null) one column's filter. All column filters AND together and compose with the active sort and hidden rows. API reference → text: string let text : string let text : string Formula source when the cell is a formula, else the literal display text. API reference → values: readonly CellScalar[] let values : readonly CellScalar [] let values : readonly CellScalar [] Numeric cells; text, booleans, errors and empty cells are null (a gap). API reference → op: "gt" | "gte" | "lt" | "lte" | "eq" | "neq" let op : "gt" | "gte" | "lt" | "lte" | "eq" | "neq" let op :
| "gt"
| "gte"
| "lt"
| "lte"
| "eq"
| "neq" value: number let value : number let value : number const cities: CellScalar[] const cities : CellScalar [] const cities : CellScalar [] API reference → Grid.distinctValues(col: number, limit?: number): CellScalar[] Grid. distinctValues (col: number, limit ?: number): CellScalar[] Grid. distinctValues (col: number, limit ?: number): CellScalar[] Distinct resolved values of a column in first-seen order. Defaults to 1,000 values for bounded filter menus; pass 0 to request an uncapped scan. API reference → Grid.hideRows(rows: readonly number[]): void Grid. hideRows (rows: readonly number[]): void Grid. hideRows (rows: readonly number[]): void Hide the given data rows (composes with filters/sort). API reference → Grid.groupRows(start: number, end: number): void Grid. groupRows (start: number, end: number): void Grid. groupRows (start: number, end: number): void Define a collapsible row group over a data-row range (end-inclusive). API reference → Grid.setGroupCollapsed(start: number, collapsed: boolean): void Grid. setGroupCollapsed (start: number, collapsed: boolean): void Grid. setGroupCollapsed (start: number, collapsed: boolean): void Collapse/expand a row group; collapsing hides its rows. API reference → type Aggregate = (col: number, op: AggregateOp) => number type Aggregate = ( col : number , op : AggregateOp ) => number ; type Aggregate = (
col : number ,
op : AggregateOp ,
) => number ; API reference → interface Grid interface Grid interface Grid Imperative grid handle for document commands, events, rendering, and teardown. Example import type { Grid } from "@sheetwrite/core" ;
function updateTotal ( grid : Grid ) {
const sheet = grid. getActiveSheet ();
const result = grid. applyTransaction ({
patches: [{ op: "set" , addr: { sheet, row: 0 , col: 0 }, value: { kind: "literal" , value: 42 } }],
});
if (result.status === "applied" ) grid. scrollToCell ({ sheet, row: 0 , col: 0 });
return grid. aggregate ( 0 , "sum" );
} See also createGrid * See also Grid.applyTransaction API reference → const rows: number const rows : number const rows : number Source field indices that group the output rows, outermost first. API reference → Grid.setFrozen(rows: number, cols?: number): void Grid. setFrozen (rows: number, cols ?: number): void Grid. setFrozen (rows: number, cols ?: number): void Pin the first rows view rows and cols columns; they stay visible while the body scrolls (0 = unfreeze that axis). Persisted on the active sheet. API reference → Grid.setZoom(zoom: number): void Grid. setZoom (zoom: number): void Grid. setZoom (zoom: number): void Content zoom factor (0.5–2): scales row/column geometry and fonts. API reference → Grid.getZoom(): number Grid. getZoom (): number Grid. getZoom (): number API reference →