Lattice Grid

api reference

Export and saved views: JavaScript Data Grid API

grid.export to Excel and CSV, grid.import from a CSV or a pasted block, grid.state, grid.views, pagination and scroll.

API reference › Export and saved views

grid.export

MethodReturnsDescription
csv(opts)string | BlobFields sanitised against formula injection.
excel(opts)Promise<Blob>Real .xlsx, written without a ZIP dependency. Large exports stream.
clipboard(opts)PromiseTSV, with the grid's own paste parser as its counterpart.
print(opts)voidSwitches virtualisation and pinning off for the printed document.
rows(mode)Row[]'all', 'visible' or 'selected'.

Excel value conversion. A data type may declare toExcelValue and excelKind, because a spreadsheet's number formats are not free-form. A time of day is written as a fraction of a day under hh:mm:ss; a duration as days under [h]:mm:ss, where the brackets are what stop Excel wrapping at 24 hours. Both stay numeric, so they still sort and subtract in the sheet.

IP columns are stored as packed integers so they sort as addresses, and declare excelKind: 'string' so the dotted form is what reaches the file. Radix columns export decimal: OOXML cannot express base 16, and staying numeric was judged worth more than display fidelity.

LatticeGrid.xlsx

A standalone multi-sheet workbook writer and a raw-cell reader, on the LatticeGrid namespace and the ESM export xlsx - no grid needed. write builds one .xlsx with a worksheet per sheets entry, from plain row arrays (a cell's JavaScript type decides its spreadsheet type: numbers, strings, booleans, Dates and null/empty) or a grid (exported exactly as grid.export.excel() would). read is the mirror, returning every sheet - or one, by sheet name or index - as { name, hidden, rows }, blanks kept in place so column positions never shift. toCsv serialises a sheet back to RFC 4180 CSV. Both reuse the core's own ZIP, styles and XML code; nothing in the page loads a third-party spreadsheet library.

MethodReturnsDescription
write(opts)Promise<Blob>Write one .xlsx with a worksheet per opts.sheets entry; filename also downloads, toArrayBuffer returns the bytes for an upload.
read(bytes, opts?)Promise<{ sheets }>Read every sheet (or one, by sheet) as { name, hidden, rows }; startRow, raw, dates and blank tune the cells.
toCsv(sheet)stringSerialise one sheet (or its rows) to RFC 4180 CSV.
const { xlsx } = await import('../packages/core/src/index.js');

// Write a two-sheet workbook from plain row arrays - no grid needed.
const bytes = await xlsx.write({
  sheets: [
    { name: 'Summary', rows: [['kind', 'count'], ['total', 10]] },
    { name: 'Data', rows: [['name', 'ok'], ['Widget', true]] },
  ],
  toArrayBuffer: true,
});

// Read it back: every sheet in order, types kept.
const wb = await xlsx.read(bytes, { raw: true });
return `${wb.sheets.map((s) => s.name).join(', ')} | ${wb.sheets[1].rows[1].join('=')}`;

grid.import

The mirror of grid.export: rows coming in from delimited text - a CSV or TSV file, or the tab-separated block a spreadsheet puts on the clipboard. The pipeline is parse, infer each column's type, map the columns onto the grid's own fields, then preview and confirm. The API is always present; set config.import to add the DOM affordances (a "Import rows from CSV…" cell-menu item, a file drop target, and paste).

MethodReturnsDescription
preview(text, opts?)ImportPreviewParse, infer and map without changing the grid - the columns, the coerced records, a sample and any warnings a confirm dialog needs.
csv(text, opts?)object[]Parse delimited text into coerced record objects, the inverse of export.csv.
apply(input, opts?)ChangeResult | nullAdd (mode: 'append', the default) or replace (mode: 'replace') the grid's rows from text, a preview or a record array. A client-side operation, so it applies to a memory-source grid; on any other source it declines rather than show rows that cannot persist.

Excel. .xlsx is read too, through the platform's own inflate (DecompressionStream) and a tag scanner in the core - the same pipeline as CSV, only async. A multi-sheet workbook reads its first visible worksheet by default; pass a sheet name or zero-based index to read another, and list the workbook's sheets (hidden ones flagged) with xlsxSheets.

const { createHeadlessGrid } = await import('../packages/core/src/index.js');

const grid = createHeadlessGrid({
  columns: [{ field: 'id' }, { field: 'age', type: 'integer' }],
  rows: [{ id: 'seed', age: 1 }],
  rowKey: 'id',
  // Opt in to the DOM affordances; the grid.import API is present either way.
  import: true,
});

// Preview changes nothing - it is what a confirm dialog shows.
const preview = grid.import.preview('id,age\nx,20\ny,30');

// Confirming appends the previewed rows; `age` arrives coerced to a number.
grid.import.apply(preview);

return `${preview.rowCount} previewed, ${grid.rows.count()} rows`;   // 2 previewed, 3 rows
const { createHeadlessGrid } = await import('../packages/core/src/index.js');

const grid = createHeadlessGrid({
  columns: [{ field: 'id' }, { field: 'age', type: 'integer' }],
  rows: [{ id: 'x', age: 20 }, { id: 'y', age: 30 }],
  rowKey: 'id',
});

// Write a two-sheet workbook so there are real .xlsx bytes to read back.
const out = await grid.export.excel({
  sheets: [{ name: 'Summary' }, { name: 'Data' }],
});
const bytes = new Uint8Array(await out.arrayBuffer());

// List the workbook's sheets, in order, hidden sheets flagged.
const sheets = await grid.import.xlsxSheets(bytes);

// Read one of them by name - a zero-based index ({ sheet: 1 }) works too.
const preview = await grid.import.previewXlsx(bytes, { sheet: 'Data' });

return `${sheets.map((s) => s.name).join(', ')} / ${preview.rowCount} rows`;

grid.state

MethodReturnsDescription
get(opts?)GridStateVersioned and serialisable: columns, columnOrder, filters, quick, sort, group, pivot, expanded, selection, pagination. scroll is omitted unless called with { scroll: true } - it is transient UI state, not view state, so a saved view does not reopen the grid scrolled to wherever it was when captured.
apply(state, opts?)objectRestore a view. Returns a report of anything it could not apply (a column that no longer exists, for instance) rather than failing silently. A scroll key in state is restored only when opts.scroll is also true; otherwise it is left alone even when present.
baseline()GridState | nullThe state the grid started in, captured once after config.state and any default view, so the baseline is the grid you shipped, not the one before your own configuration ran.
reset()object | nullPut the grid back to that baseline, as one undo entry. Clears anything the baseline does not mention, including the quick filter.
modified()booleanWhether anything has changed since construction. Lets a "restore" control disable itself rather than offering an action that would do nothing.

Scroll is opt-in, on both sides. It is transient UI state, not view state, so a saved view, the baseline and serialiseState's diff never carry it: get() omits it unless called with { scroll: true }, and apply() restores a scroll key only when it is present and apply is also called with { scroll: true } - so an old persisted state that still has one does not reopen the grid scrolled away from the top.

const { createHeadlessGrid } = await import('../packages/core/src/index.js');

const grid = createHeadlessGrid({
  rowKey: 'id',
  columns: [{ id: 'n', field: 'n' }],
  rows: [{ id: '1', n: 'a' }],
});

const hasScrollByDefault = 'scroll' in grid.state.get();
const hasScrollOptedIn = 'scroll' in grid.state.get({ scroll: true });

const ignored = grid.state.apply({ version: 2, scroll: { top: 220, left: 0 } });
const scrollIgnored = !ignored.applied.includes('scroll');

const applied = grid.state.apply({ version: 2, scroll: { top: 220, left: 0 } }, { scroll: true });
const scrollApplied = applied.applied.includes('scroll');

const result = [hasScrollByDefault, hasScrollOptedIn, scrollIgnored, scrollApplied].join(',');
grid.destroy();
return result;

grid.views

Named states the user can return to. Views supplied in config.views.saved are defined views: listed apart in the picker, and neither renamable nor deletable, refused by the model as well as hidden in the interface. Views the user saves are their own and carry rename, share, default and delete.

Storage is read first. With a storage adapter the store always reads it before anything else. Views passed in saved alongside it are shipped views: merged in as read-only entries (no rename, delete or overwrite), never replacing a stored view, never written back as the user's, and never displacing the user's stored default, a stored default wins over a shipped one. The first write after load contains exactly the user's views. Storage that already holds copies of shipped views (written by an earlier build) is de-duplicated by id without losing the user's edits. New view ids are unique across sessions and devices; the store never assigns an id it already holds, and a custom id function is honoured but checked the same way, warning once and adding a suffix on a clash.

A view is a layout, not a snapshot of clicks. save, export and import keep the configuration - columns, order, widths, pinning, visibility, sort, filters, grouping, pivot, formatting, density - and leave the current selection and expansion out by default. Applying a view likewise leaves the selection and expansion as they are. Opt them back in per section with views.capture. Views saved by an earlier build that still carry a selection or expanded section load and apply without error; the section is simply ignored unless captured.

createGrid(el, {
  views: {
    saved: [{ id: 'escalations', name: 'Escalations', description: 'Worst SLA first',
              state: { filters: { col: 'statusId', op: 'eq', value: 4 },
                       sort: [{ col: 'utilisation', dir: 'desc' }] } }],
    allowSave: true,   // false removes the save form entirely
    onShare: (payload, view) => sendView(view.name, payload),   // receive the export; default copies JSON
    local: true,       // saved views live in this browser's localStorage, no backend
    // capture: { selection: true, expanded: true }, // opt selection and expansion back in
    // storage: { read, write }, // or bring your own backend; see the note below
    // user: () => currentUser,        // { id, name }, or a function read fresh on every check
    // isAdmin: (user) => user.role === 'admin',
    // adminSeesPrivate: true,         // let an admin list private views that are not theirs
  },
});
MethodReturnsDescription
list() / get(id)object[] / objectA private view is listed only to its owner, and to an admin only with adminSeesPrivate: true; a shared view is listed to everyone.
save(name, opts?)objectCaptures the current layout - not the selection or expansion, unless views.capture opts them in. opts: id, description, shared, isDefault. A new view is stamped with the current views.user as its owner; saving over an existing one keeps the owner it already had.
apply(id)object | nullOne undo entry. Resets to the baseline first, so a view is a destination rather than a patch, the same view gives the same grid whatever was applied before it. Leaves selection and expansion alone unless the view was saved with views.capture. Never refused by ownership - open to everyone.
rename(id, name)object | nullNull for a defined view. Throws a ViewPermissionError (code: 'views/forbidden') if the view has an owner and the acting user is neither that owner nor an admin - see below.
remove(id)booleanFalse for a defined view. Throws the same ViewPermissionError as rename for a view this user may not delete.
unshare(id)object | nullStops sharing a view, leaving its name, description and state alone. Null for an unknown or defined view. Throws the same ViewPermissionError as rename.
duplicate(id, name?)object | nullA private copy, owned by whoever duplicated it, named "{name} (copy)" when the picker suggests one. Never refused by ownership: it is how a non-owner gets a layout they may change.
canEdit(view)booleanThe non-throwing twin of rename/remove/unshare/overwriting via save: whether the acting user may change this view at all. Always true while views.user is unset. A host's own button should check this before offering the action, the same way the panel does.
setDefault(id)object | nullnull clears it. A default view is applied on load, without recording an undo entry. Never gated: a non-owner may still make someone else's shared view their own default.
export(id) / import(json)objectA JSON payload. The picker's Share hands it to config.views.onShare; without one it copies the payload as JSON to the clipboard and shows a short confirmation, with a JSON download fallback where the clipboard is unavailable. The owner travels with the view both ways: an imported view keeps the owner it was exported with, not whoever ran the import.
diff(id)object | nullWhat applying a view would change.
reload()voidRe-read from storage, discarding what is in memory.
activeIdstring | null

Owners and permissions. Without views.user configured, nothing here changes: every view stays as editable to everyone as it always was. With it set, every view saved from now on records who saved it - { id, name } - and a shared view can only be renamed, overwritten (saved over by name), deleted or unshared by its owner or an admin (views.isAdmin). Everyone else can still apply it, duplicate it into a private copy of their own, and set it as their own default. A view saved before this was configured has no recorded owner and is editable only by an admin, though applying and duplicating it stay open to all. The panel shows the owner's name on a shared view and withholds - rather than merely disables - the actions a user cannot take, with the reason reachable as the row's title and aria-description. views.user may be a function, read fresh on every check, so a sign-in change takes effect on the very next click rather than requiring the grid to be rebuilt.

Two users and an admin, sharing one view

const { createTestDom, flushFrames } = await import('../packages/dom/src/renderer/testdom.js');
const { createGrid, mountPanel } = await import('../packages/dom/src/index.js');

const { root } = createTestDom();
let current = { id: 'alice', name: 'Alice' };
const grid = createGrid(root, {
  rowKey: 'id',
  columns: [{ id: 'statusId', field: 'statusId', title: 'Status' }],
  rows: [{ id: 1, statusId: 4 }],
  views: {
    user: () => current,
    isAdmin: (user) => user.id === 'admin',
  },
});
mountPanel({ grid, panel: 'views', container: root });
flushFrames();

// Alice saves a shared view: she is stamped as its owner.
const view = grid.views.save('Escalations', { shared: true });

// Bob is not the owner: the store refuses his rename, and the panel never
// offered him the button in the first place.
current = { id: 'bob', name: 'Bob' };
grid.views.reload();
flushFrames();

let refused = false;
try {
  grid.views.rename(view.id, 'Hijacked');
} catch (err) {
  refused = err.code === 'views/forbidden';
}
const row = root.querySelector('[data-view="' + view.id + '"]');
const bobSeesRename = !!(row && row.querySelector('[data-action="Rename"]'));
// canEdit agrees, without throwing - the question a host's own button asks.
const bobCanEdit = grid.views.canEdit(grid.views.get(view.id));

// Bob can still duplicate it - a private copy that is his own.
const copy = grid.views.duplicate(view.id);

// An admin may rename and unshare Alice's view, though they do not own it.
current = { id: 'admin', name: 'Admin' };
const renamedByAdmin = grid.views.rename(view.id, 'Escalations (reviewed)');
const unsharedByAdmin = grid.views.unshare(view.id);

return `${refused} | ${bobSeesRename} | ${bobCanEdit} | ${copy.owner.id} | ${renamedByAdmin.name} | ${unsharedByAdmin.shared}`;
const { createTestDom, flushFrames, TestEvent } = await import('../packages/dom/src/renderer/testdom.js');
const { createGrid, mountPanel } = await import('../packages/dom/src/index.js');

const { root } = createTestDom();
const got = [];
const grid = createGrid(root, {
  rowKey: 'id',
  columns: [{ id: 'statusId', field: 'statusId', title: 'Status' }],
  rows: [{ id: 1, statusId: 4 }],
  views: { onShare: (payload, view) => got.push(`${payload.kind}, ${view.name}`) },
});
mountPanel({ grid, panel: 'views', container: root });
flushFrames();

grid.views.save('Escalations');
flushFrames();
const share = root.querySelector('[data-action="Share"]');
share.dispatchEvent(new TestEvent('click', { bubbles: true }));
flushFrames();

// Share handed onShare exactly what grid.views.export produces, and it imports back.
const payload = grid.views.export(grid.views.list()[0].id);
return `${got[0]} | ${payload.kind} | ${grid.views.import(payload).imported.length}`;

The grid makes no network calls. storage.write is a synchronous mirror. To persist to a server, listen for view:saved, view:renamed, view:removed and view:default: each carries the one view that moved, so you can send a single record rather than diffing two lists. Because the grid does not track whether your write landed, a failed request leaves the view visible locally: catch it and call views.reload().

views.local is the no-backend option: true stores views under a default localStorage key, shared by every grid on the origin; { key: '…' } picks a key of your own, for more than one grid whose views should stay apart. Given alongside an explicit storage, storage wins and local is ignored, with a console warning, the two are never merged. Built on createLocalViewStorage, exported for direct use (a custom key, or a different Storage-shaped backing such as sessionStorage) without the local shorthand.

grid.pagination

A window over the rows the query already produced, not another query. A page change re-slices; it does not re-filter, re-sort or re-group, so paging a million rows costs nothing beyond the repaint.

MethodReturnsDescription
get(){ page, pageSize, total, pageCount, counting }total is the filtered row count, so it moves when a filter does. On a paged or remote source it is null until the server's total arrives, with counting true while the first answer is still on its way.
set({ page?, pageSize? })voidMove, resize, or both. pageSize: 0 turns paging off and shows everything. Emits page:changed once the rows have moved.

Paging over a paged or remote source

A paged or remote source holds only the rows it has fetched, so there is nothing to slice. Instead, page p is the row window [p × pageSize, (p + 1) × pageSize) of the server's answer to the current query, and moving to a page fetches the blocks that window needs - one request when the page size equals the source's own pageSize. The viewport scrolls within the page, rows still in flight draw as loading rows, and rows.get(0) is the first row of the page, exactly as on a memory grid. rows.count() is the page on screen; rows.matchCount(), rows.totalCount() and pagination.get().total are the whole result.

  • Configure both. pagination: { enabled: true, pageSize: 250 } turns the pager on; source: { mode: 'paged', pageSize: 250, fetch } sets the block the server is asked for. Matching them makes every page one request. A headless grid honours the configured page size too, with no pager to apply it.
  • A new query starts at page 0. A sort, a filter or a quick filter changes the list the server answers, so the page goes back to the first one and page:changed says so.
  • No total yet is not the end. While total is null, the pager keeps "next" enabled and pageCount counts the pages known so far plus the next one.
  • A source with no page model refuses by name. A stream or custom source that cannot window warns once (pagination:source-unsupported), shows no pager and keeps scrolling.
const { createHeadlessGrid } = await import('../packages/core/src/index.js');

const asked = [];
const grid = createHeadlessGrid({
  rowKey: 'id',
  columns: [{ field: 'id' }, { field: 'name' }],
  pagination: { enabled: true, pageSize: 250 },
  source: {
    mode: 'paged', pageSize: 250,
    fetch: async ({ range }) => {
      asked.push(`${range.start}-${range.end}`);
      const rows = [];
      for (let i = range.start; i < Math.min(range.end, 1000); i++) rows.push({ id: i, name: `row ${i}` });
      return { rows, total: 1000 };
    },
  },
});

const heard = [];
grid.on('page:changed', (e) => heard.push(e.page + 1));
const landed = new Promise((resolve) => grid.once('rows:changed', resolve));
grid.pagination.set({ page: 2 }); // the third page: rows 500 to 749
await landed;

const { page, pageCount, total } = grid.pagination.get();
const first = grid.rows.get(0).data.id;
grid.destroy();
return `page ${page + 1} of ${pageCount}, rows from ${first}, ${total} total, fetched ${asked.join(' ')}, page:changed to ${heard}`;

grid.scroll

MethodReturnsDescription
position(){ top, left }
toRow(row, align?)voidalign: 'start', 'centre', 'end'.
toColumn(id)void
to(at)voidScroll to { top, left }. left is the logical offset: zero at the content's start whichever way the grid reads.
toCell(row, colId, align?)voidScroll a cell into view, both axes in one call. row is a row key or a display index.