Load and save xlsx filesSpreadsheet
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#
- Pass a
File,Blob,ArrayBufferorUint8ArraytoimportXlsx(). - Get the file back as bytes with
exportXlsx(), or as JSON withtoJSON(). - Report failures from the
errorevent, whosecodeis'import'or'export'. - On a server, use
xlsxToJSON()andjsonToXlsx(), which need no DOM.
Open a file#
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#
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#
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.
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})`);
}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:
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, a server can open an uploaded file, change inputs, recalculate and return a new file:
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 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 }toexportXlsx()for a faster, larger file when saving often.