Write a workbook, read the cells back
Write an Excel workbook from rows and read its cells back; a broken file gives a typed error.
AGPL-3.0-onlyRuns on this page
Package: @awacloud/ooxml
Write a one-sheet workbook (a header row and three rows, a string, an
integer and a decimal column), read it back and render the cells as a table;
a truncated archive shows the typed ParseError.
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
Exporting a table of application data as a spreadsheet people open in Excel or LibreOffice, or importing one they upload, with cell types kept (a quantity is a number, not the text "240") and with a readable, typed error when the file is not what it claims to be.
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.htmlandmain.jsnext 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. - Fill
rowswith your own values: plain strings, numbers and booleans become typed cells; pass{ type: 'cell', value, t, formula }objects when you need a formula or an explicit type.
What it shows
- Wiring: one
ModuleRuntimewith@awacloud/ooxml'sfw_requireandmodules;rt.resolve('xlsx')is the typed API andrt.resolve('ooxmlErrors')carries the error classes. The@awacloud/ooxml/xlsxsubpath is not served under/vendor/ooxml/, so a page takesxlsxfrom the root. - Write:
xlsx.write({ type: 'workbook', sheets: [{ name, rows }] })returns the.xlsxbytes; each row is an array, each plain value becomes a cell whose typetis inferred (nfor numbers,sfor strings,bfor booleans) and strings go to the shared-strings part. - Read:
xlsx.read(bytes)returns{ workbook, package }; the workbook is{ type: 'workbook', sheets }and each sheet hasnameandrowsof{ type: 'cell', value, t, ref }cells.cellRef(row, col)names a cell the spreadsheet way (A1). The test checks every value and type comes back equal. - Typed errors: a truncated or foreign archive makes
read()throw aParseErrorfromooxmlErrors, with a kebab-casecodesuch asopc/…; the page catches that class, showscode: messageand clears the table, and lets anything else propagate. - Not shown: styles, merges, hyperlinks, data validation, tables,
comments and drawings on the sheet model; the
xlsxLargeBundle/xlsxFullBundlecoverage bundles;pptx.
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');
/** One sheet: a header row and three rows with a string, an integer and a decimal column. */
export function buildWorkbook() {
return {
type: 'workbook',
sheets: [{
name: 'Inventory',
rows: [
['Item', 'Quantity', 'Unit price'],
['Bolt M6', 240, 0.12],
['Washer', 1000, 0.03],
['Bracket', 12, 4.5],
],
}],
};
}
/**
* The `.xlsx` bytes: plain values become typed cells (`t` inferred: n for numbers, s for strings).
* @param {object} workbook
*/
export const write = (workbook) => XLSX.write(workbook);
/**
* Read the first sheet back as plain values, or report the package's typed
* parse error (a truncated or foreign archive) instead of throwing it.
* @param {Uint8Array} bytes
* @returns {{ name: string, rows: (string | number | boolean | null)[][], refs: string[] } | { error: string }}
*/
export function readCells(bytes) {
try {
const [sheet] = XLSX.read(bytes).workbook.sheets; // `read` returns { workbook, package }
const rows = sheet.rows.map((row) => row.map((cell) => cell.value));
return { name: sheet.name, rows, refs: sheet.rows[0].map((_, c) => XLSX.cellRef(0, c)) };
} catch (err) {
if (err instanceof ParseError) return { error: `${err.code}: ${err.message}` };
throw err;
}
}
const table = /** @type {HTMLElement} */ (document.getElementById('cells'));
const status = /** @type {HTMLElement} */ (document.getElementById('status'));
let bytes = /** @type {Uint8Array | null} */ (null);
function show(/** @type {ReturnType<typeof readCells>} */ result) {
if ('error' in result) {
table.replaceChildren();
status.textContent = result.error;
return;
}
table.replaceChildren(...result.rows.map((row, r) => {
const tr = document.createElement('tr');
for (const value of row) {
tr.appendChild(document.createElement(r === 0 ? 'th' : 'td')).textContent = String(value);
}
return tr;
}));
status.textContent = `${result.name}: ${result.rows.length} rows read back, columns ${result.refs.join(', ')}`;
}
document.getElementById('write')?.addEventListener('click', () => {
bytes = write(buildWorkbook());
show(readCells(bytes));
/** @type {HTMLButtonElement} */ (document.getElementById('corrupt')).disabled = false;
});
document.getElementById('corrupt')?.addEventListener('click', () => {
if (bytes) show(readCells(bytes.subarray(0, Math.floor(bytes.length / 2)))); // half an archive is not an archive
});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 · Write a workbook, read the cells back</title>
<link rel="stylesheet" href="../../_style/examples.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>Write a workbook, read the cells back</h1>
<p>
<button id="write" type="button">Write and read back</button>
<button id="corrupt" type="button" disabled>Read a truncated copy</button>
</p>
<p id="status" aria-live="polite"></p>
<table>
<caption>Inventory</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>