Open in a new tab

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

  1. npm install @awacloud/ooxml (it depends on @awacloud/fw).
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ and node_modules/@awacloud/ooxml/src/ at /vendor/ooxml/ (any static server).
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link. Keep the legal notice under </main>: copy ../../LICENSES/AGPL-3.0-only.txt along, or point its link at your copy.
  4. Fill rows with 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 ModuleRuntime with @awacloud/ooxml's fw_require and modules; rt.resolve('xlsx') is the typed API and rt.resolve('ooxmlErrors') carries the error classes. The @awacloud/ooxml/xlsx subpath is not served under /vendor/ooxml/, so a page takes xlsx from the root.
  • Write: xlsx.write({ type: 'workbook', sheets: [{ name, rows }] }) returns the .xlsx bytes; each row is an array, each plain value becomes a cell whose type t is inferred (n for numbers, s for strings, b for 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 has name and rows of { 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 a ParseError from ooxmlErrors, with a kebab-case code such as opc/…; the page catches that class, shows code: message and 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 / xlsxFullBundle coverage bundles; pptx.

Code

main.js

javascriptAGPL-3.0-only76 lines

// 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

htmlAGPL-3.0-only42 lines

<!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>