Birch UI v0.1
Pricing

Excel export with custom stylesPro

Export the grid view to .xlsx and restyle it to match your brand, with a title row, coloured headers, conditional fills and number formats.

Open .md

exportExcel() writes a clean, neutral workbook. For a report that goes to customers or finance you usually want your own header colours, a title above the table and highlighted rows. Build the workbook with buildExcelWorkbook(), restyle it, and write it with downloadXlsx() from @birchui/excel.

1. Set number formats on the columns#

Number formats travel with the columns, so set them once with meta.excelNumFmt:

columns.ts
import type { ColumnDef } from '@birchui/core';
import type { Order } from './orders';

export const columns: ColumnDef<Order>[] = [
  { field: 'id', header: 'Order', width: 110 },
  { field: 'customer', header: 'Customer', width: 200 },
  { field: 'status', header: 'Status', width: 110 },
  { field: 'orderedOn', header: 'Ordered', type: 'date', meta: { excelNumFmt: 'd mmm yyyy' } },
  { field: 'total', header: 'Total', type: 'number', meta: { excelNumFmt: '"$"#,##0.00' } },
  { field: 'margin', header: 'Margin', type: 'number', meta: { excelNumFmt: '0.0%' } },
];

2. Restyle the workbook#

buildExcelWorkbook() returns an XlsxWorkbook whose first sheet has one header row followed by one row per grid row, each as { cells: XlsxCell[] }. Change styles in place and insert extra rows above the header:

export-orders.ts
import { createGrid } from '@birchui/core';
import { ExcelModule } from '@birchui/grid-pro';
import { columnLetter, downloadXlsx, type XlsxCell, type XlsxCellStyle, type XlsxRow } from '@birchui/excel';
import { columns } from './columns';

const BRAND = { navy: '#1F3A5F', mist: '#EEF3F8', alert: '#FEF3F2', alertText: '#B42318' };

const headerStyle: XlsxCellStyle = {
  font: { name: 'Arial', bold: true, color: '#FFFFFF' },
  fill: BRAND.navy,
  align: 'center',
  border: { bottom: { style: 'medium', color: BRAND.navy } },
};

const grid = createGrid(document.querySelector<HTMLElement>('#orders')!, {
  columns,
  rows: orders,
  getRowId: (order) => order.id,
  modules: [ExcelModule],
});

function asRow(row: XlsxRow | XlsxCell[]): XlsxRow {
  return Array.isArray(row) ? { cells: row } : row;
}

function style(cell: XlsxRow['cells'][number], extra: XlsxCellStyle): XlsxCell {
  const base: XlsxCell = cell !== null && typeof cell === 'object' && 'value' in cell ? cell : { value: cell };
  return { ...base, style: { ...base.style, ...extra } };
}

export async function exportOrders(): Promise<void> {
  const workbook = grid.buildExcelWorkbook?.({ sheetName: 'Orders' });
  if (!workbook) return;
  const sheet = workbook.sheets[0];
  const [header, ...body] = sheet.rows.map((row) => asRow(row as XlsxRow | XlsxCell[]));
  const statusIndex = grid.getDisplayColumns().findIndex((column) => column.id === 'status');

  header.cells = header.cells.map((cell) => style(cell, headerStyle));
  header.height = 22;

  body.forEach((row, index) => {
    const cells = row.cells.map((cell) => style(cell, { font: { name: 'Arial' } }));
    const returned = statusIndex >= 0 && style(cells[statusIndex], {}).value === 'Returned';
    row.cells = cells.map((cell) =>
      returned
        ? style(cell, { fill: BRAND.alert, color: BRAND.alertText })
        : index % 2 === 1
          ? style(cell, { fill: BRAND.mist })
          : (cell as XlsxCell),
    );
  });

  const lastColumn = columnLetter(header.cells.length - 1);
  sheet.rows = [
    { cells: [{ value: 'Northwind Traders: open orders', style: { font: { name: 'Arial', size: 16, bold: true, color: BRAND.navy } } }], height: 28 },
    [`Exported ${new Date().toLocaleDateString('en-US', { dateStyle: 'long' })}`],
    [],
    header,
    ...body,
  ];
  sheet.merges = [...(sheet.merges ?? []), `A1:${lastColumn}1`];
  sheet.freeze = { ...sheet.freeze, rows: 4 };
  sheet.autoFilter = false;
  sheet.tabColor = BRAND.navy;

  await downloadXlsx(workbook, 'open-orders.xlsx');
}

columnLetter() takes a zero-based column index and returns A, B, ... AA.

How it works#

  • Every cell has a value and an optional style. Styles merge on top of what the grid wrote, such as the number format and the bold group rows, because the code spreads base.style first.
  • freeze.rows moves with the inserted title rows: the header is now on row 4, so the first four rows stay visible.
  • The grid turns on autoFilter for flat grids. An autofilter covers the first row of the sheet, so turn it off when you insert rows above the header, or set it to a range string such as 'A4:F4'.
XlsxCellStyleinterface@birchui/excelFull reference
PropertyTypeDescription
fontoptionalXlsxFont—
boldoptionalboolean—
italicoptionalboolean—
coloroptionalstring—
filloptionalstring—
numFmtoptionalstring—
alignoptional'left' | 'center' | 'right'—
valignoptional'top' | 'center' | 'bottom'—
wrapoptionalboolean—
indentoptionalnumber—
borderoptionalXlsxBorderSide | XlsxBorderSides—

Pitfalls#

  • Colours are hex strings such as #1F3A5F. Named CSS colours are not translated.
  • Row indexes change when you insert rows. Read the status column from the cells, as above, not from the grid's row index, because grouped exports add group rows.
  • Keep values native. Do not replace numbers with formatted strings to change their look; use numFmt so Excel can still sum the column.

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