Birch UI v0.1
Pricing

Excel export and importPro

Export the current grid view to a styled .xlsx file with real numbers, dates, groups and frozen headers, and import spreadsheets back into the grid.

Open .md

ExcelModule writes what the user sees in the grid to a native .xlsx file and reads spreadsheets back in. It uses the Excel Engine, which runs entirely in the browser: no server round trip and no third-party service.

Excel export and import

Loading demo…

View source

Sample data and small UI helpers are imported from the docs' demos/_shared.ts and demos/_scheduler-data.ts files.

demos/excel-export.ts
import { createGrid, type ColumnDef } from '@birchui/core';
import { AggregationModule, ExcelModule, RowGroupingModule } from '@birchui/grid-pro';
import {
  button,
  docsTheme,
  formatCurrency,
  layout,
  makeOrders,
  onDocsThemeChange,
  revenueOf,
  type Order,
} from './_shared';

export const meta = { title: 'Excel export and import', height: 480 };

const columns: ColumnDef<Order>[] = [
  { field: 'region', header: 'Region', rowGroup: true },
  { field: 'id', header: 'Order', width: 110 },
  { field: 'customer', header: 'Customer', width: 190 },
  { field: 'product', header: 'Product', width: 180 },
  { field: 'quantity', header: 'Units', type: 'number', width: 90, aggFunc: 'sum' },
  {
    id: 'revenue',
    header: 'Revenue',
    type: 'number',
    width: 130,
    valueGetter: revenueOf,
    format: formatCurrency,
    aggFunc: 'sum',
  },
  { field: 'orderDate', header: 'Ordered', type: 'date', width: 120 },
];

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const grid = createGrid<Order>(body, {
    columns,
    rows: makeOrders(1200, 33),
    getRowId: (order) => order.id,
    modules: [RowGroupingModule, AggregationModule, ExcelModule],
    groupDefaultExpanded: 1,
    rowSelection: 'multiple',
    theme: docsTheme(),
    ariaLabel: 'Orders ready for Excel export',
  });
  const run = async (task: () => Promise<unknown> | undefined, done: string) => {
    try {
      await task();
      status.textContent = done;
    } catch (error) {
      status.textContent = `Export failed: ${(error as Error).message}`;
    }
  };
  const file = document.createElement('input');
  file.type = 'file';
  file.accept = '.xlsx';
  file.hidden = true;
  const onFile = () => {
    const chosen = file.files?.[0];
    if (!chosen) return;
    run(() => grid.importExcel?.(chosen), `Imported ${chosen.name}: ${grid.getRows().length.toLocaleString()} rows.`);
    file.value = '';
  };
  file.addEventListener('change', onFile);
  toolbar.append(
    button('Download orders.xlsx', () =>
      run(
        () => grid.exportExcel?.({ fileName: 'orders-2026.xlsx', sheetName: 'Orders' }),
        'Downloaded orders-2026.xlsx with the grouped view.',
      ),
    ),
    button('Export selected rows', () =>
      run(
        () => grid.exportExcel?.({ fileName: 'selected-orders.xlsx', sheetName: 'Selected', onlySelected: true }),
        'Downloaded selected-orders.xlsx.',
      ),
    ),
    button('Import .xlsx', () => file.click()),
    file,
  );
  status.textContent = grid.exportExcel
    ? 'The workbook keeps the grouped view, number formats and column widths.'
    : 'ExcelModule is not installed.';
  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  return () => {
    file.removeEventListener('change', onFile);
    stopTheme();
    grid.destroy();
  };
}

Export the grid#

export-button.ts
import { createGrid } from '@birchui/core';
import { ExcelModule, RowGroupingModule, AggregationModule } from '@birchui/grid-pro';

const api = createGrid(container, {
  columns,
  rows: orders,
  getRowId: (row) => row.id,
  modules: [ExcelModule, RowGroupingModule, AggregationModule],
  groupBy: ['region'],
});

document.querySelector('#export')!.addEventListener('click', async () => {
  await api.exportExcel?.({ fileName: 'orders-q3.xlsx', sheetName: 'Q3 orders' });
});

exportExcel() builds the workbook, compresses it and starts a download in the browser. Column header menus also gain an Export to Excel item while the module is installed.

Option Default Effect
fileName 'export.xlsx' Download name. .xlsx is added if missing.
sheetName 'Sheet1' Worksheet name. Characters Excel does not allow are replaced and long names are shortened to 31 characters.
onlySelected false Export only the selected rows, or the active cell range when no rows are selected.
allRows false Also include the rows inside collapsed groups, as hidden outline rows the user can expand in Excel.

Like other Pro methods, the export methods are optional on the GridApi type, so call them with ?..

What the file contains#

The export reflects the current view:

  • Columns in display order, with their headers, skipping hidden columns and utility columns such as the master/detail toggle. Column widths are converted from pixels to Excel widths.
  • Rows after filtering and sorting, in the order shown. With pagination on, every page is exported, not only the one on screen. Detail panels are not exported.
  • Header row in bold on a light grey fill with a bottom border, frozen so it stays visible while scrolling. Columns pinned to the left are frozen too.
  • Autofilter on the header row for flat grids, so Excel's filter buttons are ready to use.
  • Groups as bold rows labelled with the group and its row count, such as EMEA (1204), followed by their rows indented one level per depth. Group rows carry their aggregates. Excel outline levels are set, with summary rows above their details, so users can collapse groups in Excel with the outline buttons. A group that is collapsed in the grid is exported as its summary row only; pass allRows: true to include its rows as well, hidden in a collapsed outline.
  • Grand total row in bold when groupTotals is on.
  • Pivot mode exports the cross-tab as shown, with the generated column headers.

Real values, not text#

Cells are written with their native type so that Excel can calculate with them:

Column type Written as Number format
number A number #,##0, or #,##0.00 and so on, with as many decimals as the data uses, up to four
date An Excel date, keeping the local date and time the grid shows yyyy-mm-dd, or yyyy-mm-dd hh:mm when any value has a time
boolean TRUE or FALSE
text Text, through the column's format function when it has one

A value that does not match its column type, such as 'n/a' in a number column, is written as the formatted text instead of failing.

Text cells are always stored as text, never as formulas, so a value such as =HYPERLINK(...) typed by a user is shown literally and not evaluated when the file is opened.

Custom number formats#

Set meta.excelNumFmt on a column to choose its Excel number format:

TypeScript
const columns: ColumnDef<Order>[] = [
  { field: 'id', header: 'Order' },
  { field: 'revenue', type: 'number', meta: { excelNumFmt: '"$"#,##0.00' } },
  { field: 'margin', type: 'number', meta: { excelNumFmt: '0.0%' } },
  { field: 'orderedOn', header: 'Ordered', type: 'date', meta: { excelNumFmt: 'd mmm yyyy' } },
];

The grid's own format function is not translated into an Excel format, so use excelNumFmt when the spreadsheet should look like the grid. See Styles and number formats for format codes.

Export selected rows or a range#

With onlySelected: true, the export contains:

  1. the selected rows, when any rows are selected, as a flat list;
  2. otherwise, the rows and columns of the active cell range;
  3. otherwise, the whole view.
TypeScript
await api.exportExcel?.({ fileName: 'selected-invoices.xlsx', onlySelected: true });

Customise the workbook#

To add a second sheet, a title row or a different style, build the workbook without downloading it, change it, and write it with the Excel Engine:

TypeScript
import { downloadXlsx, type XlsxWorkbook } from '@birchui/excel';

const workbook: XlsxWorkbook | undefined = api.buildExcelWorkbook?.({ sheetName: 'Orders' });
if (workbook) {
  workbook.title = 'Q3 order report';
  workbook.creator = 'Northwind Analytics';
  workbook.sheets.push({
    name: 'Notes',
    columns: [{ width: 80 }],
    rows: [
      [{ value: 'Exported from the order desk', style: { bold: true } }],
      [`Generated ${new Date().toISOString().slice(0, 10)}. Figures exclude cancelled orders.`],
    ],
  });
  await downloadXlsx(workbook, 'orders-q3.xlsx');
}

The Excel Engine guides describe the workbook model in full.

Upload instead of download#

getExcelBlob() returns the file as a Blob, ready to upload, attach to an email form or store:

TypeScript
const blob = await api.getExcelBlob?.({ sheetName: 'Orders' });
if (blob) {
  const body = new FormData();
  body.append('file', blob, 'orders.xlsx');
  await fetch('/api/reports', { method: 'POST', body });
}

Import a spreadsheet#

importExcel() reads an .xlsx file and loads its rows into the grid. Pass a File from an input or drop zone, a Blob, an ArrayBuffer or a Uint8Array.

TypeScript
const input = document.querySelector<HTMLInputElement>('#import')!;

input.addEventListener('change', async () => {
  const file = input.files?.[0];
  if (!file) return;
  const result = await api.importExcel?.(file, { sheet: 'Orders', mode: 'replace' });
  if (result?.unmappedHeaders.length) {
    console.warn(`Ignored columns: ${result.unmappedHeaders.join(', ')}`);
  }
});
Option Default Effect
sheet 0 The sheet to read, by index or by name.
mode 'replace' 'replace' calls setRows() with the imported rows; 'append' adds them with applyTransaction().
columnMap {} Map spreadsheet headers to column ids, for headers that do not match.

The first row of the sheet is the header row. Each header is matched to a grid column, in this order:

  1. an explicit entry in columnMap, such as { 'Cust. name': 'customer' };
  2. the column's header text, ignoring case and extra spaces;
  3. the column's field or id.

Each column is matched at most once. Headers that match nothing are reported in unmappedHeaders and their data is ignored. Rows without any value are skipped.

Values are converted to the column type the same way paste converts text. Dates from Excel become dates in the form your column already uses, such as ISO strings, and text columns receive dates as YYYY-MM-DD. Values are stored with the column's valueSetter when it has one, otherwise at its field, including nested paths such as customer.name.

The promise resolves to an ExcelImportResult:

TypeScript
interface ExcelImportResult<TRow> {
  rows: TRow[];
  mappedColumns: Record<string, string>;
  unmappedHeaders: string[];
}

A sheet name or index that does not exist logs a warning and resolves to an empty result without touching the grid.

Files written with other tools#

Import reads standard .xlsx workbooks, including shared and inline strings, booleans, cached formula results, error values and both the 1900 and 1904 date systems. Styles other than date formats are not read. Password-protected workbooks are not supported. See Reading files for the details.

Reference#

The option and result types ExcelExportOptions, ExcelImportOptions and ExcelImportResult are listed in the @birchui/grid-pro API reference. For the workbook model, see the @birchui/excel reference.

↑ ↓ to move, Enter to open, Esc to close