# Toolbar, export and print

> PivotToolbar built-in and custom items, export to Excel, PDF and CSV and print from the toolbar or the instance API with a lazily loaded writer, and the onBeforeExport and onExport events.

Canonical: https://salmonui.dev/docs/pivot-table/toolbar-and-export

## Toolbar

`PivotToolbar` is a `toolbar` of
built-in and custom items bound to the store. Use it standalone or through
the `toolbar` prop of `PivotTable`:

```tsx
<PivotToolbar pivot={pivot} items={['fieldList', 'totals', 'formatting', 'export']} exportWriters={exportWriters} />
<PivotTable pivot={pivot} toolbar={['fieldList', 'expandAll', 'collapseAll', 'export']} exportWriters={exportWriters} />
```

| Item | Kind | Action |
| --- | --- | --- |
| `fieldList` | button | Opens the popup [field list](https://salmonui.dev/docs/pivot-table/field-list) |
| `totals` | menu | Subtotals on or off, grand totals for both, rows, columns or none |
| `subtotals` | toggle button | Subtotals on or off (`aria-pressed`) |
| `grandTotals` | menu | Grand totals for both, rows, columns or none |
| `formatting` | menu | Number format…, Conditional format…, Calculated field… |
| `numberFormat`, `conditionalFormat`, `calculatedField` | button | Opens that [editor](https://salmonui.dev/docs/pivot-table/editors) |
| `export` | menu | Excel, CSV, PDF, Print |
| `expandAll`, `collapseAll` | button | Expands or collapses every member on both axes |

The default items are `['fieldList', 'totals', 'formatting', 'export']`.
Custom items are objects: `{ id, label, onClick, disabled }`, or `{ id,
render }` for any content:

```tsx
<PivotToolbar
  pivot={pivot}
  items={[
    'fieldList',
    { id: 'reset', label: 'Reset', onClick: () => pivot.setModel(initialModel) },
    { id: 'layout', render: () => <LayoutSwitch /> },
    'export',
  ]}
/>
```

Arrow keys move between items (one tab stop); ArrowDown opens a menu.
Menus load on first open. The dialogs the toolbar opens are rendered by a
`PivotTable` bound to the same store, so keep one mounted.

## Export and print

| Instance API (`ref`) | Toolbar | Needs a writer |
| --- | --- | --- |
| `api.exportToExcel(options)` | Export > Excel | yes |
| `api.exportToPdf(options)` | Export > PDF | yes |
| `api.exportToCsv(options)` | Export > CSV | no |
| `api.print()` | Export > Print | no |

The XLSX and PDF writers live in `@salmonui/export`, a separate
package; `@salmonui/pivot-table` never imports it.
Pass a loader, a dynamic import, so the writers load on the first export
and stay out of your initial JavaScript:

```tsx
const exportWriters = { pivot: () => import('@salmonui/export/pivot') };

<PivotTable pivot={pivot} toolbar={['export']} exportWriters={exportWriters} />
```

Without `exportWriters` the Excel and PDF items are disabled and the
instance methods report an error; CSV and print still work, built from the
result in `@salmonui/pivot-table`: one header line of column paths
(`2026 / Q1 / Sum of Amount`) and one line per visible row with raw
numbers. With `exportWriters`, CSV goes through `exportPivot()` like the
other formats, with the same column-path header and raw numbers by
default; `api.exportToCsv({ csv: { values: 'formatted' } })` writes the
formatted text instead. Print renders the result as a plain table in
a hidden frame and opens the browser's print dialog.

```ts
await api.exportToExcel({ fileName: 'sales', rowLayout: 'tabular' });
await api.exportToPdf({ fileName: 'sales' });
```

`fileName` defaults to `pivot`. Each method resolves with the written
file, `{ fileName, mimeType, data }` (null when cancelled);
`download: false` returns it without starting a download, for example to
upload it.
Other options pass through to `exportPivot()` (row layout, column filter,
styles, cell hooks, sheet names); see [Export](https://salmonui.dev/docs/pivot-table/export)
for the file formats and every option, including server-side export.

### Events

| Event | Payload |
| --- | --- |
| `onBeforeExport` | `{ format: 'xlsx' \| 'csv' \| 'pdf' \| 'print', fileName }`; `preventDefault()` cancels |
| `onExport` | the same, after the file is written |

A writer error goes to `onError` with `action: 'export'` (thrown when no
`onError` is set).

## On-demand code

Export follows the rule of every pivot feature: there is nothing to
register. The
export and print code is a chunk of `@salmonui/pivot-table` loaded on the first
export, the writers load through your `exportWriters` loader, and the
toolbar's menus load on first open.

Why: a registration list makes the bundle depend on a list you maintain
by hand, and a forgotten entry fails only at run time. Splitting at the
feature boundary keeps the initial chunk small (the pivot bundle budgets
are release gates) without any registration step.

Turn each feature on with its prop or part: `toolbar` or `PivotToolbar`,
`fieldList="popup"` or `PivotFieldList`, `axisBar` or `PivotAxisBar`,
`drillThrough`, and `exportWriters` for Excel and PDF export; the
calculated field, number format and conditional format editors open
from the toolbar or the instance API with no prop.

### Live demo: Toolbar, export and saved reports

Live demo: https://salmonui.dev/demos/pivot-table/pivot-table-toolbar-export

The built-in toolbar items plus a custom item, Excel, CSV and PDF export and print with cancellable export events, a saved report list over getState and restoreState, and persistState.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { PivotTable, type PivotExportWriters, type PivotModelInput, type PivotTableApi, type PivotTableState, type PivotToolbarItem, type PivotToolbarItemId, type PivotFieldDefinition } from '@salmonui/pivot-table';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';
import { TextField } from '@salmonui/inputs/text-field';

type Sale = { region: string; country: string; product: string; year: string; amount: number; units: number };

const COUNTRIES: Record<string, string[]> = { Asia: ['Japan', 'India'], Europe: ['France', 'Germany'], Americas: ['Brazil', 'Canada'] };
const PRODUCTS = ['Bikes', 'Helmets', 'Gloves'];

function makeSales(): Sale[] {
  const rows: Sale[] = [];
  let n = 0;
  for (const [region, countries] of Object.entries(COUNTRIES)) {
    for (const country of countries) {
      for (const product of PRODUCTS) {
        for (const year of ['2025', '2026']) {
          n++;
          const amount = ((n * 449) % 1500) + 100;
          rows.push({ region, country, product, year, amount, units: (amount % 19) + 1 });
        }
      }
    }
  }
  return rows;
}

const SALES = makeSales();

// Captions for the headers, the axis bar and the field list (the raw field names otherwise).
const FIELDS: PivotFieldDefinition<Sale>[] = [
  { field: 'region', caption: 'Region', type: 'string' },
  { field: 'country', caption: 'Country', type: 'string' },
  { field: 'product', caption: 'Product', type: 'string' },
  { field: 'year', caption: 'Year', type: 'string' },
  { field: 'amount', caption: 'Amount', type: 'number' },
  { field: 'units', caption: 'Units', type: 'number' },
];

const MODEL: PivotModelInput = {
  rows: [{ field: 'region' }, { field: 'country' }],
  columns: [{ field: 'year' }],
  values: [{ field: 'amount', aggregate: 'sum' }],
  formats: { amount: { number: { style: 'currency', currency: 'USD', maximumFractionDigits: 0 } } },
};

/** The Excel and PDF writers load on the first export (CSV and print need no writer). */
const WRITERS: PivotExportWriters = { pivot: () => import('@salmonui/export/pivot') };

type Report = { name: string; state: PivotTableState };

/** Built-in and custom toolbar items, export and print with their events, saved reports and persistence. */
export default function PivotTableToolbarExportDemo() {
  const tableRef = useRef<PivotTableApi<Sale>>(null);
  const [cancelExports, setCancelExports] = useState(false);
  const [log, setLog] = useState<string[]>([]);
  const push = (line: string) => setLog((items) => [line, ...items].slice(0, 6));
  // Report management over app storage (here React state; a real app would use its backend).
  const [reports, setReports] = useState<Report[]>([]);
  const [name, setName] = useState('My report');
  const [selected, setSelected] = useState('');

  const save = () => {
    const state = tableRef.current?.getState();
    if (!state || !name.trim()) return;
    setReports((list) => [...list.filter((r) => r.name !== name.trim()), { name: name.trim(), state }]);
    setSelected(name.trim());
    push(`saved "${name.trim()}"`);
  };
  const load = () => {
    const report = reports.find((r) => r.name === selected);
    if (report && tableRef.current?.restoreState(report.state)) push(`loaded "${report.name}"`);
  };
  const rename = () => {
    if (!selected || !name.trim()) return;
    setReports((list) => list.map((r) => (r.name === selected ? { ...r, name: name.trim() } : r)));
    push(`renamed "${selected}" to "${name.trim()}"`);
    setSelected(name.trim());
  };
  const remove = () => {
    setReports((list) => list.filter((r) => r.name !== selected));
    push(`deleted "${selected}"`);
    setSelected('');
  };

  const toolbar: (PivotToolbarItemId | PivotToolbarItem)[] = [
    'fieldList',
    'totals',
    'subtotals',
    'grandTotals',
    'formatting',
    'export',
    'expandAll',
    'collapseAll',
    { id: 'new', label: 'New report', onClick: () => tableRef.current?.restoreState({ version: 1, pivotModel: { ...tableRef.current.pivot.model, rows: [], columns: [], values: [], filters: [] } }) },
  ];

  return (
    <div>
      <div className="demo-toolbar" role="group" aria-label="Export from code">
        <Button variant="outline" onClick={() => void tableRef.current?.exportToExcel({ fileName: 'sales' })}>
          exportToExcel()
        </Button>
        <Button variant="outline" onClick={() => void tableRef.current?.exportToCsv({ fileName: 'sales' })}>
          exportToCsv()
        </Button>
        <Button variant="outline" onClick={() => void tableRef.current?.exportToPdf({ fileName: 'sales' })}>
          exportToPdf()
        </Button>
        <Button variant="outline" onClick={() => void tableRef.current?.print()}>
          print()
        </Button>
        <Checkbox checked={cancelExports} onCheckedChange={(checked) => setCancelExports(checked)}>
          Cancel exports in onBeforeExport
        </Checkbox>
      </div>
      <div className="demo-toolbar" role="group" aria-label="Reports">
        <label>
          Report name
          <TextField aria-label="Report name" value={name} onValueChange={(next) => setName(next)} style={{ inlineSize: '12em' }} />
        </label>
        <Button variant="outline" onClick={save}>
          Save
        </Button>
        <label>
          Saved
          <Select aria-label="Saved" data={[{ value: '', label: '(none)' }, ...reports.map((r) => ({ value: r.name, label: r.name }))]} value={selected} onValueChange={(next) => setSelected(next == null ? '' : String(next))} />
        </label>
        <Button variant="outline" onClick={load} disabled={!selected}>
          Load
        </Button>
        <Button variant="outline" onClick={rename} disabled={!selected}>
          Rename to name
        </Button>
        <Button variant="outline" onClick={remove} disabled={!selected}>
          Delete
        </Button>
      </div>
      <PivotTable<Sale>
        ref={tableRef}
        data={SALES}
        fields={FIELDS}
        defaultPivotModel={MODEL}
        toolbar={toolbar}
        fieldList="popup"
        exportWriters={WRITERS}
        // The model is saved under `salmon-pivot-table:docs-toolbar-export` and restored on the next visit.
        persistState={{ id: 'docs-toolbar-export', version: '1' }}
        onBeforeExport={(event) => {
          if (cancelExports) {
            event.preventDefault();
            push(`${event.format} export cancelled`);
          }
        }}
        onExport={(event) => push(`exported ${event.format}: ${event.fileName}`)}
        locale="en-US"
        height={320}
        aria-label="Sales report"
      />
      <div className="demo-log" aria-label="Export and report log">
        {log.length ? (
          <ol>
            {log.map((line, i) => (
              <li key={`${i}-${line}`}>{line}</li>
            ))}
          </ol>
        ) : (
          'Export from the toolbar or the buttons, or save a report, change the layout and load it back. Reload the page: the last report is restored.'
        )}
      </div>
    </div>
  );
}
```
