# Export

> Excel, PDF and CSV export of the grid view with hooks, events, several grids per workbook, server export and on-demand writers.

Canonical: https://salmonui.dev/docs/data-grid/export

The grid exports what it shows: the current sort, filter, search and
grouping, over every page (`pages: 'all'`, the default) or the current page
(`pages: 'current'`). Three instance methods cover the
formats:

```tsx
const file = await api.exportToExcel({ fileName: 'orders' }); //
await api.exportToPdf({ orientation: 'landscape' });          //
await api.exportToCsv({ delimiter: ';', bom: true });         //
```

Each resolves to `{ fileName, mimeType, data }` and downloads it; pass
`download: false` to keep only the file, and `downloadBlob(file)` saves any
file or `Blob` later (it is a no-op on the server).

## Writers load on demand

CSV escapes spreadsheet formulas by default: text starting with `=`, `+`,
`-`, `@`, tab or CR (also after leading whitespace) gets a leading `'`; real
numbers stay as they are. `escapeFormulas: false` restores raw output.

CSV is a pure writer in `@salmonui/data-grid/engine` and needs nothing. Excel and
PDF writers live in `@salmonui/export` and are passed as loaders, so the
default Data Grid bundle never contains them:

```tsx
const writers = {
  excel: () => import('@salmonui/export/xlsx'),
  pdf: () => import('@salmonui/export/pdf'),
};
<DataGrid exportWriters={writers} toolbar={['exportExcel', 'exportPdf', 'exportCsv', 'print']} contextMenu />
```

The toolbar and context-menu export items run the export with default
options. Without a loader the matching item is disabled and its title says
why. To customize what an item does, register a handler:
`api.registerCommandHandler('export.excel', () => void api.exportToExcel({ ... }))`.
A status with a spinner shows while a file is produced; it is a
polite `role="status"` element, so screen readers announce "Exporting…"
(`localeText.exporting`).

## Options

- `rows` exports custom data with the grid's columns, for example
  `api.getSelectedRows()`; `includeHiddenColumns` adds hidden
  columns; `columns` picks and relabels columns; `fileName` names
  the file.
- Excel: `sheetName`, `styles` (`header`, `row`, `groupCaption`,
  `aggregate`), `header` / `footer` rows, `freezeHeader`, and
  `mergeRepeatedValues`, which merges equal adjacent values of a column
  into one cell.
- PDF: `orientation`, `pageSize`, `header` / `footer` with `{page}` and
  `{pages}`, `columnOverflow: 'fit' | 'paginate'`, `font` (see
  below), and `mergeRepeatedValues` as in Excel. In PDF a merged run
  restarts at every page (the value is drawn again at the top of the next
  page) and stops at group captions and detail blocks.
- Formatting follows the column formats. Lookup columns export
  their display text, not the key. Stacked headers export as merged
  header rows, split at pinned-column edges like the grid header.

```tsx
// Only the rows the user selected, with the grid's columns.
api.exportToExcel({ rows: api.getSelectedRows(), fileName: 'selected-orders' });
// Hidden columns too.
api.exportToCsv({ includeHiddenColumns: true });
```

## Several grids in one workbook

`grids` adds further grids to the same Excel file. `layout:
'sheets'` (the default) writes one sheet per grid, named by `sheetNames`;
`layout: 'stacked'` writes them one below the other on a single sheet with
`gap` blank rows between them:

```tsx
api.exportToExcel({ grids: [targetsApi], layout: 'sheets', sheetNames: ['Orders', 'Targets'] });
api.exportToExcel({ grids: [targetsApi], layout: 'stacked', gap: 2 });
```

PDF takes one grid per file. Multiple-grid export runs in the browser only;
the server entry exports one grid.

### Multiple-grid and outline limits

Two limits are intentional. Multiple-grid export composes the live export models of several grids in one client call;
a server job would need every grid's query and data source, so there is no
server-side multiple-grid export. Excel outlines stop at 7 levels, the
SpreadsheetML maximum: deeper group and detail rows are still written at
level 7, and child grids nested deeper than seven levels are left out. To
export several grids into one file, call `exportToExcel({ grids })` (or
`exportXlsx` from `@salmonui/export/xlsx` with every grid) on the
client.

## Hooks and events

Hooks are functions on the export options and return patches:

- `cell(ctx)` returns `{ value, text, style, formula, colSpan, rowSpan,
  image }` per data cell. `formula` writes a live Excel formula,
  with or without the leading `=`. **Security:** never build `formula` from untrusted input (user data, imported files, API responses); it is written as a live formula that runs when the workbook is opened. Text cells never
  execute: formula-like text stays a string and gets Excel's quote-prefix
  style, with no visible `'`. `colSpan` / `rowSpan` merge
  the cell with the following cells and rows in Excel and PDF; the
  covered cells are not written. In PDF a column span is clipped to its
  column page set (`columnOverflow: 'paginate'`), and a row span stops at
  a group caption or detail block and continues on the next page with the
  cell drawn again.
- The grid's own spans (column `colSpan` / `rowSpan`, `mergeCells`) are
  view settings and do not reach the export: return the same spans from
  `cell(ctx)`, or pass `mergeRepeatedValues`, to merge exported cells.
- A column with `renderCell` exports its value text; React output never
  becomes export text by itself. Return `{ text }` from `cell` for the
  exported text of a templated column (a `text` patch without `value`
  writes a text cell, even on a number, boolean or date column), and
  `image` with PNG or JPEG bytes
  (`{ data, type, width, height }`) to draw a picture in the Excel or PDF
  cell; CSV keeps the text.
- `headerCell(ctx)`, `aggregateCell(ctx)` and `groupCaption(ctx)` customize
  header, aggregate and caption cells; group captions and footer, group
  footer and caption aggregates are exported.
- `detail(ctx)` writes a detail block after a row: text lines
  (`{ text: [...] }`) or a nested export model (`{ model }`). `hierarchy`
  picks the rows: `'expanded'` (default, rows whose detail is expanded;
  collapsed rows get no block, also from the hook), `'all'` or `'none'`.
A grid without detail rows (no `renderDetail` or `childGrid`)
  has no expansion state, so its `detail` hook runs for every row unless
  the mode is `'none'`. Excel nests detail blocks one outline level
  deeper and clamps at 7 outline levels.

```tsx
api.exportToExcel({
  hierarchy: 'all',
  detail: ({ row }) => (row.note ? { text: [`Note: ${row.note}`] } : null),
  cell: ({ column, row }) => {
    if (column.field !== 'shipped') return undefined;
    const label = row.shipped ? 'Shipped' : 'Pending';
    return { value: label, text: label };
  },
});
```

`onBeforeExport` runs before every export and cancels it with
`preventDefault()`; `onExport` receives the finished file. Both
carry `format: 'excel' | 'pdf' | 'csv'` and the options.

## Unicode text in PDF

The built-in PDF fonts are the standard Helvetica faces, which cover only
Western European text; other characters print as `?`. Pass TrueType bytes
(`.ttf`, or the first face of a `.ttc`) as `font` and every text of the PDF
is drawn with that font, embedded as a subset with a `ToUnicode` map, so the
text stays searchable and copyable. CJK, Cyrillic, Greek and
Arabic (with shaping and basic bidi) work when the font covers them.
`font: { regular, bold }` adds a real bold face; without it bold is
synthetic. No font ships with the package, and CFF-based OpenType (`.otf`)
fonts are not supported.

```tsx
const font = new Uint8Array(await (await fetch('/fonts/NotoSansJP-Regular.ttf')).arrayBuffer());
api.exportToPdf({ font, header: '注文' });
```

## Server export

`@salmonui/data-grid/engine/export-server` builds the same export on a server.
The client sends its view as `serializeDataGridState(api.getState())`; the
server rebuilds a headless grid from the same rows and column definitions
with `createExportDataGrid`, or passes `{ rows, columns, state }` straight to
`exportToResponse` (a Web `Response` for route handlers) or
`exportToStream` (a Node `Writable` or Web `WritableStream`):

```ts
// app/api/export/route.ts (Next.js route handler)
import { exportToResponse } from '@salmonui/data-grid/engine/export-server';

export async function POST(request: Request) {
  const { format, state } = await request.json();
  return exportToResponse({ rows, columns, state, timeZone: 'UTC' }, { format, fileName: 'orders' });
}
```

The sort, filters, search, grouping and column order of the client apply;
selection and scroll do not. Keep the column definitions in a module both
sides import. Lookup columns export their display text on the server too;
remote lookup sources are loaded before the file is written. Multiple-grid
workbooks stay client-side.

The demo below runs every option above; its Server export buttons call a
route like the one shown.

### Live demo: Export and print

Live demo: https://salmonui.dev/demos/data-grid/export-print

Excel, PDF and CSV export of 10,000 grouped rows with stacked headers, aggregates, lookup text, templates, hidden columns, selected rows, detail blocks, a second grid in the same workbook, an embedded PDF font and a server export route; writers load on demand; print of every row of the scope.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Select } from '@salmonui/dropdowns/select';
import {
  downloadBlob,
  DataGrid,
  serializeDataGridState,
  type DataGridAggregateRow,
  type DataGridApi,
  type DataGridColumn,
  type DataGridExportWriters,
} from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { exportOrderColumns, exportOrders, regionTargets, type RegionTarget } from '../../lib/export-demo';
import type { Order } from '../../lib/fixtures';
import { demoFetch } from '../../lib/remote';

// Lookup rows of the `category` column: the grid and the export show `title`, not the key.
const categories = [
  { code: 'Coffee', title: 'Coffee beans' },
  { code: 'Tea', title: 'Loose-leaf tea' },
  { code: 'Equipment', title: 'Brewing equipment' },
];

const columns: DataGridColumn<Order>[] = [
  // The shared core definitions (also used by the server export route), plus React-only fields.
  // Amount is widened so its footer sum fits.
  ...exportOrderColumns.map((column): DataGridColumn<Order> =>
    column.field === 'discount' ? { ...column, printable: false } : column.field === 'amount' ? { ...column, width: 170 } : column,
  ),
  { field: 'category', header: 'Category', width: 150, lookup: { data: categories, keyField: 'code', displayField: 'title' } },
  {
    field: 'shipped',
    header: 'Status',
    width: 110,
    // A React template never becomes export text by itself; the `cell` hook below supplies it.
    renderCell: ({ value }) => (
      <span className="demo-badge" {...(value ? { 'data-tone': 'success' } : {})}>
        {value ? 'Shipped' : 'Pending'}
      </span>
    ),
  },
  // Hidden in the grid; `includeHiddenColumns: true` exports it.
  { field: 'note', header: 'Note', width: 200, hidden: true },
];

const targetColumns: DataGridColumn<RegionTarget>[] = [
  { field: 'region', header: 'Region', width: 120 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'target', header: 'Target', type: 'number', format: 'C0', align: 'end', width: 130 },
  { id: 'stretch', header: 'Stretch (+10%)', type: 'number', format: 'C0', align: 'end', width: 140, valueGetter: (row) => Math.round(row.target * 1.1) },
];

// Module-level: the dynamic imports keep both writers out of the page bundle until first use.
const writers: DataGridExportWriters = {
  excel: () => import('@salmonui/export/xlsx'),
  pdf: () => import('@salmonui/export/pdf'),
};

const aggregates: DataGridAggregateRow<Order>[] = [{ columns: [{ field: 'amount', type: 'sum', format: 'C2' }] }];

// A 12 x 12 PNG drawn into the Status cell of shipped orders.
const FLAG_PNG = Uint8Array.from(
  atob('iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAE0lEQVR4nGN4EWtPEDGMKhqMigCvX9pBVGrfQQAAAABJRU5ErkJggg=='),
  (c) => c.charCodeAt(0),
);

const PRINT_SCOPE_OPTIONS = [
  { value: 'all', label: 'All pages' },
  { value: 'page', label: 'Current page' },
];

export default function ExportPrintDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const targetsApi = useRef<DataGridApi<RegionTarget> | null>(null);
  const fontInput = useRef<HTMLInputElement | null>(null);
  const [log, push] = useEventLog();
  const [scope, setScope] = useState<'all' | 'page'>('all');

  const serverExport = async (format: 'excel' | 'csv') => {
    const grid = api.current;
    if (!grid) return;
    const response = await demoFetch('/api/export', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ format, state: serializeDataGridState(grid.getState()) }),
    });
    const blob = await response.blob();
    push(`server export ${format}: ${response.status}, ${blob.size} bytes`);
    downloadBlob(blob, format === 'csv' ? 'orders-server.csv' : 'orders-server.xlsx');
  };

  return (
    <>
      <div className="demo-toolbar" aria-label="Export and print">
        <Button
          variant="outline"
          onClick={() =>
            void api.current?.exportToExcel({
              fileName: 'orders',
              sheetName: 'Orders',
              // excelQueryCellInfo: highlight large orders.
              cell: ({ column, value }) => (column.field === 'amount' && typeof value === 'number' && value > 1000 ? { style: { bold: true, color: '#B00020' } } : undefined),
            })
          }
        >
          Excel with a cell hook
        </Button>
        <Button variant="outline" onClick={() => void api.current?.exportToPdf({ orientation: 'landscape', header: 'Orders', footer: 'Page {page} of {pages}' })}>
          PDF, landscape
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            // exportGroupCaption / excelAggregateQueryCellInfo: rewrite captions and aggregate cells, and count the calls.
            const calls = { captions: 0, aggregates: 0 };
            void api.current
              ?.exportToCsv({
                fileName: 'orders-by-country',
                groupCaption: (ctx) => {
                  calls.captions++;
                  return `${ctx.formattedKey} (${ctx.count} orders)`;
                },
                aggregateCell: (ctx) => {
                  calls.aggregates++;
                  return ctx.placement === 'footer' ? { text: `Total ${ctx.text}` } : undefined;
                },
              })
              .then(() => push(`hooks: groupCaption ${calls.captions}, aggregateCell ${calls.aggregates}`));
          }}
        >
          CSV with caption and aggregate hooks
        </Button>
        <Button variant="outline" onClick={() => void api.current?.exportToCsv({ pages: 'current', fileName: 'orders-page' })}>
          CSV of the current page
        </Button>
        <label>
          Print scope
          <Select aria-label="Print scope" data={PRINT_SCOPE_OPTIONS} value={scope} onValueChange={(value) => value != null && setScope(value as 'all' | 'page')} />
        </label>
      </div>
      <div className="demo-toolbar" aria-label="Export options">
        <Button
          variant="outline"
          onClick={() => {
            const rows = api.current?.getSelectedRows() ?? [];
            if (rows.length === 0) push('select rows first (Ctrl or Shift click)');
            // custom rows with the grid's columns.
            else void api.current?.exportToExcel({ fileName: 'selected-orders', rows });
          }}
        >
          Excel of the selected rows
        </Button>
        <Button variant="outline" onClick={() => void api.current?.exportToCsv({ fileName: 'orders-with-notes', includeHiddenColumns: true })}>
          CSV with hidden columns
        </Button>
        <Button
          variant="outline"
          onClick={() =>
            void api.current?.exportToExcel({
              fileName: 'orders-templates',
              // Templated column: its text (and an image for shipped orders) comes from the hook.
              cell: ({ column, row }) => {
                if (column.field !== 'shipped') return undefined;
                const label = row.shipped ? 'Shipped' : 'Pending';
                return { text: label, ...(row.shipped ? { image: { data: FLAG_PNG, type: 'png' as const, width: 12, height: 12 } } : {}) };
              },
            })
          }
        >
          Excel with template text and images
        </Button>
        <Button
          variant="outline"
          onClick={() =>
            void api.current?.exportToExcel({
              fileName: 'orders-details',
              // a detail block after every row that has a note.
              hierarchy: 'all',
              detail: ({ row }) => (row.note ? { text: [`Note: ${row.note}`] } : null),
            })
          }
        >
          Excel with detail rows
        </Button>
        <Button
          variant="outline"
          onClick={() =>
            void api.current?.exportToExcel({ fileName: 'orders-and-targets', grids: targetsApi.current ? [targetsApi.current] : [], layout: 'sheets', sheetNames: ['Orders', 'Targets'] })
          }
        >
          Workbook: both grids, one sheet each
        </Button>
        <Button variant="outline" onClick={() => void api.current?.exportToExcel({ fileName: 'orders-stacked', grids: targetsApi.current ? [targetsApi.current] : [], layout: 'stacked', gap: 2 })}>
          Workbook: both grids stacked
        </Button>
        <Button variant="outline" onClick={() => fontInput.current?.click()}>
          PDF with a TrueType font…
        </Button>
        {/* The native file input stays hidden; the button above opens its file dialog. */}
        <input
          ref={fontInput}
          type="file"
          hidden
          aria-label="PDF with a TrueType font"
          accept=".ttf,.ttc,font/ttf"
          onChange={async (event) => {
            const file = event.target.files?.[0];
            event.target.value = '';
            if (!file) return;
            // the font is embedded (subsetted) so any script it covers prints.
            const font = new Uint8Array(await file.arrayBuffer());
            await api.current?.exportToPdf({ fileName: 'orders-unicode', font, header: 'Заказы · 注文 · الطلبات', orientation: 'landscape' });
          }}
        />
        <Button variant="outline" onClick={() => void serverExport('excel')}>
          Server export (Excel)
        </Button>
        <Button variant="outline" onClick={() => void serverExport('csv')}>
          Server export (CSV)
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Orders to export and print"
        ref={api}
        data={exportOrders}
        columns={columns}
        height={420}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        selection={{ multiple: true }}
        sorting
        grouping={{ groupBy: ['country'] }}
        aggregates={aggregates}
        paging={{ pageSize: 100 }}
        toolbar={['exportExcel', 'exportPdf', 'exportCsv', 'print']}
        // The grid is read-only here: the context menu offers copy and the exports only.
        contextMenu={['copy', 'exportExcel', 'exportPdf', 'exportCsv']}
        exportWriters={writers}
        printing={{ scope }}
        onBeforeExport={(event) => push(`beforeExport ${event.format} (${event.source})`)}
        onExport={(event) => push(`export ${event.format}: ${event.file.fileName}`)}
        onBeforePrint={(event) => push(`beforePrint ${event.scope} (${event.source})`)}
        onAfterPrint={() => push('afterPrint')}
      />
      <div className="demo-toolbar" aria-label="Targets export" style={{ marginBlockStart: 'var(--salmon-space-4)' }}>
        <Button
          variant="outline"
          onClick={() =>
            void targetsApi.current?.exportToExcel({
              fileName: 'targets',
              // equal adjacent regions become one merged cell.
              mergeRepeatedValues: true,
              // the stretch column is written as a live formula.
              cell: ({ column, row }) => (column.id === 'stretch' ? { formula: `ROUND(${row.target}*1.1,0)` } : undefined),
            })
          }
        >
          Targets: merged regions and formulas
        </Button>
        <Button
          variant="outline"
          onClick={() =>
            void targetsApi.current?.exportToPdf({
              fileName: 'targets',
              // equal adjacent regions become one merged cell, in PDF too.
              mergeRepeatedValues: true,
              // a cell hook span covers the target and stretch cells of one row.
              cell: ({ column, rowId }) => (rowId === 'pt' && column.field === 'target' ? { text: 'Under review', colSpan: 2 } : undefined),
            })
          }
        >
          Targets PDF: merged regions and a spanned cell
        </Button>
      </div>
      <DataGrid<RegionTarget>
        aria-label="Regional targets"
        ref={targetsApi}
        data={regionTargets}
        getRowId={(row) => row.id}
        columns={targetColumns}
        height="auto"
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        exportWriters={writers}
        onExport={(event) => push(`targets export ${event.format}: ${event.file.fileName}`)}
      />
      <EventLog entries={log} />
    </>
  );
}
```

## API reference

See [`DataGridExportOptions`](https://salmonui.dev/docs/reference/data-grid/DataGridExportOptions),
[`DataGridExcelExportOptions`](https://salmonui.dev/docs/reference/data-grid/DataGridExcelExportOptions),
[`DataGridPdfExportOptions`](https://salmonui.dev/docs/reference/data-grid/DataGridPdfExportOptions),
[`DataGridCsvExportOptions`](https://salmonui.dev/docs/reference/data-grid/DataGridCsvExportOptions),
[`DataGridExportWriters`](https://salmonui.dev/docs/reference/data-grid/DataGridExportWriters)
and the [`@salmonui/export`](https://salmonui.dev/docs/reference#export)
writers in the API reference.
