# Load and save xlsx files

> Open xlsx files from a file input, a URL or drag and drop, save them back to a server as xlsx or workbook JSON, and convert files on the server without the component.

Users bring budgets and rate cards as Excel files and expect to get Excel files back. This recipe opens xlsx files in the spreadsheet component from a file picker, a URL and drag and drop, saves edits to a server, and converts files on the server without the component.

## Steps

1. Pass a `File`, `Blob`, `ArrayBuffer` or `Uint8Array` to `importXlsx()`.
2. Get the file back as bytes with `exportXlsx()`, or as JSON with `toJSON()`.
3. Report failures from the `error` event, whose `code` is `'import'` or `'export'`.
4. On a server, use `xlsxToJSON()` and `jsonToXlsx()`, which need no DOM.

## Open a file

```ts title="rate-card-editor.ts"
import { createSpreadsheet } from '@birchui/spreadsheet';

const sheet = createSpreadsheet(document.querySelector<HTMLElement>('#rate-card')!, { height: 560 });
const fileInput = document.querySelector<HTMLInputElement>('#open-xlsx')!;

fileInput.addEventListener('change', async () => {
  const file = fileInput.files?.[0];
  if (!file) return;
  await sheet.importXlsx(file).catch(() => undefined);
  fileInput.value = '';
});

sheet.on('error', ({ code, message }) => {
  if (code === 'import' || code === 'export') showToast(message);
});

sheet.on('sheetChange', () => {
  statusLine.textContent = `${sheet.getSheetNames().length} sheets loaded`;
});
```

`importXlsx()` replaces the workbook, clears the undo history and emits `sheetChange`. When the file cannot be read, the promise rejects and the `error` event fires, so catching the promise and showing the event's message is enough.

### From a URL

```ts
async function openFromServer(url: string) {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`Could not download ${url} (${response.status})`);
  await sheet.importXlsx(await response.arrayBuffer());
}

await openFromServer('/api/rate-cards/2027/file');
```

### By drag and drop

```ts
const host = sheet.element;
host.addEventListener('dragover', (event) => event.preventDefault());
host.addEventListener('drop', (event) => {
  event.preventDefault();
  const file = [...(event.dataTransfer?.files ?? [])].find((f) => f.name.toLowerCase().endsWith('.xlsx'));
  if (file) void sheet.importXlsx(file).catch(() => undefined);
});
```

## Save

Choose the format by what happens next. Store xlsx when people download the file again; store workbook JSON when your own code reads it, for example to recalculate it on a server.

**xlsx** (`save-xlsx.ts`)

```ts
async function saveAsXlsx(rateCardId: string) {
  const bytes = await sheet.exportXlsx();
  const response = await fetch(`/api/rate-cards/${rateCardId}/file`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' },
    body: bytes,
  });
  if (!response.ok) throw new Error(`Saving failed (${response.status})`);
}
```

**JSON** (`save-json.ts`)

```ts
async function saveAsJson(rateCardId: string) {
  const response = await fetch(`/api/rate-cards/${rateCardId}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(sheet.toJSON()),
  });
  if (!response.ok) throw new Error(`Saving failed (${response.status})`);
}
```

For a plain download, call `sheet.downloadXlsx('rate-card-2027.xlsx')`.

### Save automatically

Listen to `cellChange` and `sheetChange` and save after a pause:

```ts
let timer: ReturnType<typeof setTimeout> | undefined;
const scheduleSave = () => {
  clearTimeout(timer);
  timer = setTimeout(() => void saveAsJson('2027'), 1500);
};
sheet.on('cellChange', scheduleSave);
sheet.on('sheetChange', scheduleSave);
```

## Convert on a server

`xlsxToJSON()` and `jsonToXlsx()` run in Node and workers. Combined with the [headless engine](https://docs.birchui.com/spreadsheet/headless-engine.md), a server can open an uploaded file, change inputs, recalculate and return a new file:

```ts title="server/rate-card.ts"
import { createFormulaEngine, isCellError, jsonToXlsx, xlsxToJSON } from '@birchui/spreadsheet';

const licenseKey = process.env.BIRCHUI_LICENSE_KEY;

export async function applyIndexation(upload: Uint8Array, indexRate: number) {
  const workbook = await xlsxToJSON(upload, { licenseKey });
  const engine = createFormulaEngine();
  engine.fromJSON(workbook);
  engine.setCell('Assumptions', 'B2', indexRate);

  const total = engine.getValue('Summary', 'B10');
  if (isCellError(total)) throw new Error(`The rate card returned ${total.code} in Summary!B10`);

  return { total, file: await jsonToXlsx(engine.toJSON(), { licenseKey }) };
}
```

## Pitfalls

- **Unsaved edits are replaced.** `importXlsx()` replaces the whole workbook and clears undo. Ask before opening a file over edited data.
- **Formulas Excel recalculates.** Some functions are evaluated differently, or only by Excel. See [What round-trips](https://docs.birchui.com/spreadsheet/xlsx.md#what-round-trips) before promising identical results.
- **License key on the server.** The component uses its own `licenseKey`; the standalone functions take `{ licenseKey }` on each call.
- **Large files.** Pass `{ compress: false }` to `exportXlsx()` for a faster, larger file when saving often.

## Related

- [xlsx import and export](https://docs.birchui.com/spreadsheet/xlsx.md).
- [The workbook JSON](https://docs.birchui.com/spreadsheet/sheets.md#the-workbook-json).
- [Add custom worksheet functions](https://docs.birchui.com/recipes/spreadsheet-custom-functions.md).
