Lattice Grid Buy a licence

developer guide

Excel and CSV Export from a Data Grid

Export writes the grid as the reader left it, sorted, filtered and grouped, to Excel or to CSV, with no separate export library to add or license. Hidden columns can be included or left out, and a byte order mark keeps accented text intact when the file is opened.

Developer guideExport and clipboard › Excel and CSV Export from a Data Grid

Export

CSV, Excel, clipboard, print

grid.export.csv({ download: true, fileName: 'circuits' });
grid.export.excel({ download: true, sheetName: 'Circuits' });
grid.export.clipboard({ headers: true, rows: 'range' });
grid.export.print();

Exports follow what the user is looking at, the current filter, sort and column order, formatted values, and only the columns they may read.

Two options for a file somebody opens in Excel: hidden, bom, executed

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

const grid = createHeadlessGrid({
  rowKey: 'id',
  rows: [{ id: 1, name: 'Ann', cost: 9 }],
  columns: [{ field: 'id' }, { field: 'name' }, { field: 'cost', layout: { hidden: true } }],
});
const plain = grid.export.csv({ rows: 'all' });
const wide = grid.export.csv({ rows: 'all', hidden: true, bom: true });
const head = (text) => text.replace('\uFEFF', '').split('\r\n')[0];
return (`plain ${head(plain)} | wide ${head(wide)} | bom ${plain.charCodeAt(0) === 0xFEFF} then ${wide.charCodeAt(0) === 0xFEFF}`);

hidden: true carries the columns the grid is hiding into the file - the column a reader collapsed is still a column the spreadsheet wants. A column that opted out with export.csv: false, or that the reader may not see, is still excluded. bom: true writes the UTF-8 byte-order mark, which is what stops Excel guessing the encoding and rendering every accented name as mojibake.

On the server

A user asks to export half a million rows. You can ship them all to the browser to be formatted, or write the export server-side and watch it drift from what the grid shows. The headless core is the third option.

The same code, in Node

import { createHeadlessGrid } from '@toclocoinc/lattice-grid';

const grid = createHeadlessGrid({ columns, rows: fromDatabase });
grid.state.apply(savedView.state);
return grid.export.csv();

A saved view is a serialisable state object, so the server applies exactly what the user set up, using exactly the code the browser uses. The £1,234.50 in the file is the £1,234.50 on the screen because it came out of the same formatter. 50,000 rows filtered, sorted and written to CSV takes about 100ms.