Import a spreadsheet the user picks
Import an .xlsx the user picks: its sheets, typed cells and formulas, and a typed error if broken.
AGPL-3.0-onlyRuns on this page
Package: @awacloud/ooxml
Pick an .xlsx (or press "Try a sample"), read it in the page with
xlsx.read, choose a sheet and see its first 20 rows, each cell with its
value and its type; a truncated or foreign file shows the typed
ParseError. Nothing is uploaded.
Uses @awacloud/ooxml (AGPL-3.0-only) over @awacloud/fw (Apache-2.0). This example's code is AGPL-3.0-only.
When to use it
Importing data people keep in Excel or LibreOffice — a price list, an inventory, a set of readings — into a web application, on their machine: the workbook is read into memory, every sheet is offered, and the cells arrive typed (a quantity is a number, a flag is a boolean, a total keeps its formula), so the import code does not guess from strings.
Copy-paste steps
npm install @awacloud/ooxml(it depends on@awacloud/fw).- Serve
node_modules/@awacloud/fw/src/at/vendor/fw/andnode_modules/@awacloud/ooxml/src/at/vendor/ooxml/(any static server). - Copy
index.html,main.jsandstyle.cssnext to each other and openindex.htmlthrough that server. The../../_style/examples.csslink is optional: copy that file along, or delete the link. Keep the legal notice under</main>: copy../../LICENSES/AGPL-3.0-only.txtalong, or point its link at your copy. - Replace
renderwith your own import:importWorkbook(bytes).sheetsgives every sheet's rows of{ value, type, formula? }cells.
What it shows
- Wiring: one
ModuleRuntimewith@awacloud/ooxml'sfw_requireandmodules;rt.resolve('xlsx')is the typed API andrt.resolve('ooxmlErrors')carries the error classes. - One import path: the file input and the "Try a sample" button both
end in
load(name, bytes). The sample is a two-sheet workbook written byxlsx.writein the page (an order list with aSUMtotal, thirty daily readings), so the page shows itself without a file. - Read:
xlsx.read(bytes)returns{ workbook, package, unmodelledParts }; each sheet ofworkbook.sheetshasnameandrowsof{ type: 'cell', value, t, formula?, ref }cells whosevalueis already typed: a number, a string, a boolean, ornullfor an empty cell. A formula cell keeps its formula text (SUM(B2:B4)) and the value the spreadsheet last computed. - Types a person reads:
cellType(cell)names each cellnumber,text,boolean,formula,errororempty; the table shows it under the value. - Typed errors: a truncated or foreign file makes
read()throw aParseErrorfromooxmlErrorswith a kebab-casecodesuch asopc/invalid-zip; the page showsname: code: message, empties the sheet list and the table, and lets any other error propagate. - Not shown: styles and number formats (a date stays its serial
number), merges, hyperlinks, tables, comments and drawings; the
xlsxLargeBundle/xlsxFullBundlecoverage bundles;.xls,.odsand.csvfiles.
Code
main.js
// SPDX-License-Identifier: AGPL-3.0-only
import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { fw_require, modules } from '@awacloud/ooxml';
const rt = new ModuleRuntime();
rt.registerAll([...fw_require, ...modules]);
const XLSX = rt.resolve('xlsx');
const { ParseError } = rt.resolve('ooxmlErrors');
export const MAX_ROWS = 20; // the rows a sheet shows: enough to recognise what was imported
/** A two-sheet workbook written by the package's own writer, so the page runs without a file. */
export function buildSample() {
const orders = [['Item', 'Qty', 'Paid'], ['Bolt M6', 240, true], ['Washer', 1000, false], ['Bracket', 12, true]];
orders.push(['Total', { type: 'cell', value: 1252, t: 'n', formula: 'SUM(B2:B4)' }]);
const days = Array.from({ length: 30 }, (_, i) => [i + 1, (i + 1) / 2]);
const sheets = [{ name: 'Orders', rows: orders }, { name: 'Readings', rows: [['Day', 'Reading'], ...days] }];
return XLSX.write({ type: 'workbook', sheets });
}
/** A cell's type as a person says it; `read` already typed the value (a number is a number). @param {any} cell */
export function cellType(cell) {
if (cell?.formula) return 'formula';
if (cell?.value === null || cell?.value === undefined) return 'empty';
return cell.t === 'e' ? 'error' : ({ number: 'number', boolean: 'boolean' })[typeof cell.value] ?? 'text';
}
const typed = (/** @type {any} */ c) => ({ value: c?.value ?? null, type: cellType(c), formula: c?.formula });
/** @typedef {{ name: string, rows: ReturnType<typeof typed>[][] }} Sheet */
/** Every sheet as rows of typed cells, or a truncated or foreign file's typed ParseError as a message. */
export function importWorkbook(/** @type {Uint8Array} */ bytes) {
try {
const { sheets } = XLSX.read(bytes).workbook; // `read` returns { workbook, package, unmodelledParts }
const rows = (/** @type {any} */ s) => Array.from(s.rows, (r) => Array.from(r ?? [], typed));
return { sheets: sheets.map((/** @type {any} */ s) => ({ name: s.name, rows: rows(s) })) };
} catch (err) {
if (err instanceof ParseError) return { error: `${err.code}: ${err.message}` };
throw err;
}
}
const input = /** @type {HTMLInputElement} */ (document.getElementById('file'));
const select = /** @type {HTMLSelectElement} */ (document.getElementById('sheet'));
const table = /** @type {HTMLElement} */ (document.getElementById('cells'));
const status = /** @type {HTMLElement} */ (document.getElementById('status'));
let book = /** @type {{ name: string, sheets: Sheet[] } | null} */ (null);
/** @param {HTMLElement} parent @param {string} tag @param {object} [props] */
const add = (parent, tag, props = {}) => Object.assign(parent.appendChild(document.createElement(tag)), props);
function render() {
table.replaceChildren();
const sheet = book?.sheets.find((s) => s.name === select.value);
if (!book || !sheet) return;
for (const row of sheet.rows.slice(0, MAX_ROWS)) {
const tr = add(table, 'tr');
for (const { value, type, formula } of row) {
const td = add(tr, 'td');
add(td, 'span', { className: 'value', textContent: value === null ? '' : String(value) });
add(td, 'span', { className: 'type', textContent: formula ? `${type} =${formula}` : type });
}
}
const shown = `${Math.min(sheet.rows.length, MAX_ROWS)} of ${sheet.rows.length} row(s)`;
status.textContent = `${book.name}: ${book.sheets.length} sheet(s); ${sheet.name} shows ${shown}`;
}
/** The one import path, for a picked file and for the sample. @param {string} name @param {Uint8Array} bytes */
function load(name, bytes) {
const result = importWorkbook(bytes);
book = 'error' in result ? null : { name, ...result };
select.replaceChildren();
for (const s of book?.sheets ?? []) add(select, 'option', { value: s.name, textContent: s.name });
select.disabled = book === null;
if ('error' in result) status.textContent = `${name}: ${result.error}`;
render();
}
const pick = async (/** @type {File} */ file) => load(file.name, new Uint8Array(await file.arrayBuffer()));
input.addEventListener('change', () => { if (input.files?.[0]) pick(input.files[0]); });
document.getElementById('sample')?.addEventListener('click', () => load('sample.xlsx', buildSample()));
select.addEventListener('change', render);index.html
<!doctype html>
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ooxml · Import a spreadsheet the user picks</title>
<link rel="stylesheet" href="../../_style/examples.css">
<link rel="stylesheet" href="./style.css">
<script type="importmap">
{ "imports": {
"@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/",
"@awacloud/ooxml": "/vendor/ooxml/main.js", "@awacloud/ooxml/": "/vendor/ooxml/" } }
</script>
<script type="module" src="./main.js"></script>
</head>
<body>
<main>
<h1>Import a spreadsheet the user picks</h1>
<p>
<label for="file">Workbook (.xlsx)</label>
<input id="file" type="file" accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
<button id="sample" type="button">Try a sample</button>
</p>
<p>The file never leaves the page: it is read in memory.</p>
<p>
<label for="sheet">Sheet</label>
<select id="sheet" disabled></select>
</p>
<p id="status" aria-live="polite"></p>
<table>
<caption>The first 20 rows, each cell with its type</caption>
<tbody id="cells"></tbody>
</table>
</main>
<!-- aln:begin (AGPL-3.0 sections 0, 5d and 13; derived by _harness/contract.js legalNotice, checked by C7) -->
<footer id="legal" aria-label="Legal notices">
<p>Copyright (c) 2026 AwaCloud SAS. This page is free software under the GNU Affero General Public License,
version 3 only (AGPL-3.0-only), with ABSOLUTELY NO WARRANTY:
<a href="../../LICENSES/AGPL-3.0-only.txt">licence text</a>.</p>
<p>It runs these packages, each with its own LICENSE and NOTICE file (third-party notices included):</p>
<ul>
<li>@awacloud/fw · Apache-2.0</li>
<li>@awacloud/ooxml · AGPL-3.0-only</li>
</ul>
</footer>
<!-- aln:end -->
</body>
</html>style.css
/* SPDX-License-Identifier: AGPL-3.0-only */
#cells .type { display: block; font-size: var(--ex-step--1, 0.875rem); color: var(--ex-muted, #6b7280); }