# Build a multi-sheet Excel report

> Write a styled monthly report with a summary sheet, a detail sheet and per-depot outlines using writeXlsx, with cross-sheet formulas and cached values.

Finance wants the monthly field service report as an Excel file: a summary on the first sheet, every work order on the second, and a per-depot breakdown that folds open. This recipe builds that workbook as plain data and writes it with `writeXlsx()`, in the browser, a worker or Node.

## Steps

1. Define shared styles once: header, currency, dates, totals.
2. Build the detail sheet first, because the summary's formulas refer to its rows.
3. Build the summary with `SUMIFS` formulas that point at the detail sheet, and supply cached values.
4. Build the breakdown with outline levels.
5. Write the workbook with `writeXlsx()` or download it with `downloadXlsx()`.

## Styles

```ts title="report-styles.ts"
import type { XlsxCellStyle } from '@birchui/excel';

export const styles = {
  title: { bold: true, font: { size: 16, color: '#1F3A5F' } },
  header: {
    bold: true,
    color: '#FFFFFF',
    fill: '#1F3A5F',
    valign: 'center',
    border: { bottom: { style: 'thin', color: '#0F1F33' } },
  },
  gbp: { numFmt: '"£"#,##0.00' },
  hours: { numFmt: '0.0' },
  date: { numFmt: 'dd mmm yyyy' },
  percent: { numFmt: '0%' },
  total: { bold: true, border: { top: { style: 'thin' }, bottom: { style: 'double' } } },
} satisfies Record<string, XlsxCellStyle>;
```

## The report

```ts title="monthly-report.ts"
import { cellRef, writeXlsx, type XlsxSheet, type XlsxWorkbook } from '@birchui/excel';
import { styles } from './report-styles';

export interface WorkOrder {
  orderNo: string;
  depot: string;
  technician: string;
  completed: Date;
  hours: number;
  labour: number;
  parts: number;
  firstTimeFix: boolean;
}

const header = (labels: string[]) => labels.map((value) => ({ value, style: styles.header }));

export async function monthlyReport(month: string, orders: WorkOrder[]): Promise<Uint8Array> {
  const lastRow = orders.length + 1;

  const detail: XlsxSheet = {
    name: 'Work orders',
    freeze: { rows: 1 },
    autoFilter: true,
    columns: [
      { width: 12 },
      { width: 14 },
      { width: 20 },
      { width: 13, style: styles.date },
      { width: 8, style: styles.hours },
      { width: 12, style: styles.gbp },
      { width: 12, style: styles.gbp },
      { width: 13, style: styles.gbp },
      { width: 10 },
    ],
    rows: [
      { cells: header(['Work order', 'Depot', 'Technician', 'Completed', 'Hours', 'Labour', 'Parts', 'Total', 'First fix']), height: 22 },
      ...orders.map((order, index) => {
        const row = index + 2;
        return [
          order.orderNo,
          order.depot,
          order.technician,
          order.completed,
          order.hours,
          order.labour,
          order.parts,
          { formula: `F${row}+G${row}`, value: order.labour + order.parts },
          order.firstTimeFix,
        ];
      }),
    ],
  };

  const depots = [...new Set(orders.map((order) => order.depot))].sort();
  const totalFor = (depot: string) =>
    orders.filter((o) => o.depot === depot).reduce((sum, o) => sum + o.labour + o.parts, 0);
  const grandTotal = orders.reduce((sum, o) => sum + o.labour + o.parts, 0);
  const firstFixRate = orders.filter((o) => o.firstTimeFix).length / Math.max(orders.length, 1);

  const summary: XlsxSheet = {
    name: 'Summary',
    tabColor: '#1F3A5F',
    columns: [{ width: 26 }, { width: 14, style: styles.gbp }, { width: 12 }],
    merges: ['A1:C1'],
    rows: [
      [{ value: `Field service report, ${month}`, style: styles.title }],
      [],
      header(['Depot', 'Revenue', 'Work orders']),
      ...depots.map((depot, index) => [
        depot,
        { formula: `SUMIFS('Work orders'!H2:H${lastRow},'Work orders'!B2:B${lastRow},A${index + 4})`, value: totalFor(depot) },
        {
          formula: `COUNTIFS('Work orders'!B2:B${lastRow},A${index + 4})`,
          value: orders.filter((o) => o.depot === depot).length,
        },
      ]),
      [
        { value: 'Total', style: styles.total },
        {
          value: { formula: `SUM(${cellRef(3, 1)}:${cellRef(depots.length + 2, 1)})`, value: grandTotal },
          style: { ...styles.gbp, ...styles.total },
        },
        { value: { formula: `SUM(C4:C${depots.length + 3})`, value: orders.length }, style: styles.total },
      ],
      [],
      [
        'First-time fix rate',
        {
          value: { formula: `COUNTIF('Work orders'!I2:I${lastRow},TRUE)/COUNTA('Work orders'!A2:A${lastRow})`, value: firstFixRate },
          style: styles.percent,
        },
      ],
    ],
  };

  const breakdown: XlsxSheet = {
    name: 'By depot',
    outlineSummaryBelow: false,
    freeze: { rows: 1 },
    columns: [{ width: 30 }, { width: 10, style: styles.hours }, { width: 14, style: styles.gbp }],
    rows: [
      { cells: header(['Depot / technician', 'Hours', 'Revenue']) },
      ...depots.flatMap((depot) => {
        const inDepot = orders.filter((o) => o.depot === depot);
        const technicians = [...new Set(inDepot.map((o) => o.technician))].sort();
        return [
          {
            cells: [depot, inDepot.reduce((s, o) => s + o.hours, 0), totalFor(depot)],
            style: { bold: true, fill: '#E8EEF7' },
          },
          ...technicians.map((technician) => {
            const own = inDepot.filter((o) => o.technician === technician);
            return {
              cells: [
                { value: technician, style: { indent: 1 } },
                own.reduce((s, o) => s + o.hours, 0),
                own.reduce((s, o) => s + o.labour + o.parts, 0),
              ],
              outlineLevel: 1,
            };
          }),
        ];
      }),
    ],
  };

  const workbook: XlsxWorkbook = {
    title: `Field service report ${month}`,
    creator: 'Fleetwise Operations',
    created: new Date(),
    sheets: [summary, detail, breakdown],
  };
  return writeXlsx(workbook);
}
```

The summary comes first in `sheets`, so Excel opens on it, but it is built after the detail sheet because its formulas depend on the detail's row count.

## Deliver the file

**Browser** (`download-report.ts`)

```ts
const bytes = await monthlyReport('November 2026', orders);
const url = URL.createObjectURL(
  new Blob([bytes], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }),
);
const link = Object.assign(document.createElement('a'), { href: url, download: 'field-service-2026-11.xlsx' });
link.click();
URL.revokeObjectURL(url);
```

**Node** (`scripts/monthly-report.ts`)

```ts
import { writeFile } from 'node:fs/promises';
import { setLicenseKey } from '@birchui/license';

setLicenseKey(process.env.BIRCHUI_LICENSE_KEY!);
const orders = await db.workOrders.completedIn('2026-11');
await writeFile('reports/field-service-2026-11.xlsx', await monthlyReport('November 2026', orders));
```

If you build the workbook object without calling `writeXlsx()` yourself, `downloadXlsx(workbook, 'field-service-2026-11')` writes and downloads it in one call.

## How it works

- Column styles apply to every cell in the column, so number formats are set once per column rather than per cell. A cell's own style is merged over the column and row styles.
- Formulas are written in Excel's English syntax without the leading `=`. The engine does not calculate them; Excel recalculates on open. The cached `value` is what previews and other apps show before that.
- Sheet names with spaces are quoted in formulas: `'Work orders'!H2:H40`.
- `outlineLevel: 1` on the technician rows groups them under their depot row, and `outlineSummaryBelow: false` puts the fold button on the depot row above them.

## Pitfalls

- **Dates are written in UTC.** Build `completed` with `Date.UTC()` or from ISO date strings, or a late-evening job can land on the next day. See [Cells](https://docs.birchui.com/excel/writing.md#cells).
- **Overlapping merges** are skipped with a warning, because Excel refuses to open such files.
- **Sheet name rules.** Names longer than 31 characters or containing `[ ] : * ? / \` are changed, which breaks formulas that refer to the original name. Keep names short and plain.
- **Large reports.** For tens of thousands of rows, build the workbook in a [worker](https://docs.birchui.com/excel/workers.md) so the page stays responsive.

## Related

- [Writing workbooks](https://docs.birchui.com/excel/writing.md).
- [Styles](https://docs.birchui.com/excel/styles.md) and [number formats](https://docs.birchui.com/excel/styles.md#number-formats).
- [Freeze panes, outlines and merges](https://docs.birchui.com/excel/layout.md).
- [Build a critical path report](https://docs.birchui.com/recipes/gantt-critical-path-report.md).
