Birch UI v0.1
Pricing

Import an Excel file into a gridExcel

Read an uploaded .xlsx file with readXlsx, turn its rows into typed records with sheetToObjects, validate them and show them in a grid for review.

Open .md

Users often arrive with a spreadsheet: a price list, a customer export, a stock count. This recipe reads the file in the browser with the Excel Engine, validates each row, and shows the result in a grid where bad rows are flagged before anything is saved.

1. Read the file#

read-price-list.ts
import { readXlsx, sheetToObjects, type XlsxPrimitive } from '@birchui/excel';

export async function readPriceList(file: File): Promise<Record<string, XlsxPrimitive>[]> {
  const workbook = await readXlsx(file);
  const sheet = workbook.sheets.find((candidate) => candidate.name === 'Prices') ?? workbook.sheets[0];
  if (!sheet) throw new Error(`${file.name} contains no worksheets`);
  return sheetToObjects(sheet);
}

readXlsx accepts a File, Blob, ArrayBuffer or Uint8Array and returns every sheet as rows of values: strings, numbers, booleans, Date for date-formatted cells, and null for empty cells. sheetToObjects uses the first row as keys and skips empty rows. Pass { headerRow: 2 } when the header is on the third row, below a title.

2. Validate and convert#

price-rows.ts
import type { XlsxPrimitive } from '@birchui/excel';

export interface PriceRow {
  id: string;
  sku: string;
  product: string;
  unitPrice: number | null;
  validFrom: string | null;
  problems: string[];
}

const isoDate = (value: Date) =>
  `${value.getUTCFullYear()}-${String(value.getUTCMonth() + 1).padStart(2, '0')}-${String(value.getUTCDate()).padStart(2, '0')}`;

export function toPriceRows(records: Record<string, XlsxPrimitive>[]): PriceRow[] {
  const seen = new Set<string>();
  return records.map((record, index) => {
    const problems: string[] = [];
    const sku = String(record['SKU'] ?? '').trim();
    const price = record['Unit price'];
    const validFrom = record['Valid from'];

    if (!sku) problems.push('SKU is missing');
    else if (seen.has(sku)) problems.push('Duplicate SKU');
    seen.add(sku);
    if (typeof price !== 'number' || price <= 0) problems.push('Unit price must be a positive number');
    if (validFrom !== null && validFrom !== undefined && !(validFrom instanceof Date)) {
      problems.push('Valid from is not a date');
    }

    return {
      id: `row-${index + 2}`,
      sku,
      product: String(record['Product'] ?? ''),
      unitPrice: typeof price === 'number' ? price : null,
      validFrom: validFrom instanceof Date ? isoDate(validFrom) : null,
      problems,
    };
  });
}

The id uses the spreadsheet row number (index + 2, after the header), so users can find a flagged row in Excel. Dates are read in UTC; format them with the getUTC* methods, as above, to keep the calendar date the sheet shows.

3. Show the rows for review#

price-import.ts
import { createGrid, type ColumnDef } from '@birchui/core';
import { readPriceList } from './read-price-list';
import { toPriceRows, type PriceRow } from './price-rows';

const columns: ColumnDef<PriceRow>[] = [
  { id: 'line', header: 'Row', width: 80, valueGetter: (row) => Number(row.id.slice(4)), type: 'number' },
  { field: 'sku', header: 'SKU', width: 130, editable: true },
  { field: 'product', header: 'Product', flex: 1, editable: true },
  { field: 'unitPrice', header: 'Unit price', type: 'number', editable: true },
  { field: 'validFrom', header: 'Valid from', type: 'date', editable: true, editor: 'date' },
  {
    id: 'problems',
    header: 'Problems',
    width: 280,
    valueGetter: (row) => row.problems.join('; '),
    cellClass: (ctx) => (ctx.row?.problems.length ? 'import-problem' : undefined),
  },
];

const grid = createGrid<PriceRow>(document.querySelector<HTMLElement>('#import-preview')!, {
  columns,
  rows: [],
  getRowId: (row) => row.id,
  rowClass: (row) => (row.data?.problems.length ? 'import-row-invalid' : undefined),
  emptyMessage: 'Choose a price list to preview it here.',
});

const input = document.querySelector<HTMLInputElement>('#price-file')!;
const summary = document.querySelector<HTMLElement>('#import-summary')!;

input.addEventListener('change', async () => {
  const file = input.files?.[0];
  if (!file) return;
  try {
    const rows = toPriceRows(await readPriceList(file));
    grid.setRows(rows);
    const invalid = rows.filter((row) => row.problems.length > 0).length;
    summary.textContent = `${rows.length} rows read, ${invalid} need attention.`;
  } catch (error) {
    summary.textContent = `Could not read ${file.name}: ${error instanceof Error ? error.message : String(error)}`;
  }
});
price-import.css
.lq-grid .lq-row.import-row-invalid {
  background: color-mix(in srgb, var(--lq-danger) 8%, var(--lq-bg));
}

.lq-grid .lq-cell.import-problem {
  color: var(--lq-danger);
}

Users can fix values in place. Re-run the validation on edit to update the flags:

TypeScript
grid.on('cellValueChanged', () => grid.setRows(toPriceRows(grid.getRows().map(toRecord))));

function toRecord(row: PriceRow): Record<string, string | number | Date | null> {
  return {
    SKU: row.sku,
    Product: row.product,
    'Unit price': row.unitPrice,
    'Valid from': row.validFrom ? new Date(`${row.validFrom}T00:00:00Z`) : null,
  };
}

Pitfalls#

  • Headers must match exactly. sheetToObjects uses header text as keys, including spaces and case. Normalize them if your users edit the template.
  • Formulas give cached results. A formula cell returns the value Excel last calculated. Files produced by tools that do not store results give null.
  • Large files. readXlsx also runs in a Web Worker, which keeps the page responsive for files with hundreds of thousands of rows; see Workers.
  • Password-protected workbooks are not supported and make readXlsx reject.

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