Open in a new tab

ods.fromArrays of a header row and three rows → bytes → read → cells with their value types, rendered as an HTML table; a truncated archive shows the typed ParseError. The OpenDocument counterpart of ooxml/xlsx-sheet.

Uses @awacloud/odf (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 an OpenDocument spreadsheet, or importing one, with the cell types kept (float for numbers, string for text) and a readable, typed error when the file is not what it claims to be.

Copy-paste steps

  1. npm install @awacloud/odf (it depends on @awacloud/fw).
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ and node_modules/@awacloud/odf/src/ at /vendor/odf/ (node serve.js from the examples root does this; any static server works).
  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: strings, numbers, booleans and Dates become typed cells; ods.cell(value, { styleName, formula }) builds one by hand.

What it shows

  • Wiring: one ModuleRuntime with @awacloud/odf's fw_require and modules; rt.resolve('ods') is the API and rt.resolve('odfErrors') carries the error classes. The @awacloud/odf/ods subpath is not served under /vendor/odf/, so a page takes ods from the root.
  • Write: ods.fromArrays([{ name, rows }]) builds { spreadsheet: { tables } } with one typed cell per primitive (valueType float, string, boolean, date; value as the ODF string); ods.write(doc) returns the package bytes — the mimetype entry comes first and uncompressed, as the format requires.
  • Read: ods.read(bytes) returns { mimetype, spreadsheet, meta, package, … }; each table has name and rows of cells with value and valueType; ods.toText(result) gives tab-separated rows. The test checks every value and type comes back.
  • Typed errors: a truncated or foreign archive makes read() throw a ParseError from odfErrors whose code starts with odf/; the page catches that class, shows code: message, clears the table, and lets anything else propagate.
  • Not shown: formulas and styles on cells, column definitions, named styles, odp, charts, math and forms, the odsLargeBundle / odsFullBundle coverage bundles and the opt-in extras.

Code

main.js

javascriptAGPL-3.0-only78 lines

// SPDX-License-Identifier: AGPL-3.0-only
import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { fw_require, modules } from '@awacloud/odf';

const rt = new ModuleRuntime();
rt.registerAll([...fw_require, ...modules]);
const ODS = rt.resolve('ods');
const { ParseError } = rt.resolve('odfErrors');

/** One sheet from arrays: a header row and three rows with a string, an integer and a decimal column. */
export function buildSpreadsheet() {
    return ODS.fromArrays([{
        name: 'Inventory',
        rows: [
            ['Item', 'Quantity', 'Unit price'],
            ['Bolt M6', 240, 0.12],
            ['Washer', 1000, 0.03],
            ['Bracket', 12, 4.5],
        ],
    }]);
}

/**
 * The `.ods` bytes: each primitive became a typed cell (`valueType` float, string, boolean or date).
 * @param {object} doc
 */
export const write = (doc) => ODS.write(doc);

/**
 * Read the first sheet back as `{ value, valueType }` pairs, or report the
 * package's typed parse error (a truncated or foreign archive) instead of
 * throwing it.
 * @param {Uint8Array} bytes
 * @returns {{ name: string, rows: { value: string, valueType: string }[][], text: string } | { error: string }}
 */
export function readCells(bytes) {
    try {
        const result = ODS.read(bytes); // { mimetype, spreadsheet: { tables }, meta, package, … }
        const [table] = result.spreadsheet.tables;
        const rows = table.rows.map((row) => row.cells.map(({ value, valueType }) => ({ value, valueType })));
        return { name: table.name, rows, text: ODS.toText(result) };
    } 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 cell of row) {
            const td = tr.appendChild(document.createElement(r === 0 ? 'th' : 'td'));
            td.textContent = cell.value;
            td.title = cell.valueType;
        }
        return tr;
    }));
    const types = result.rows[1].map((c) => c.valueType).join(', ');
    status.textContent = `${result.name}: ${result.rows.length} rows read back (${types})`;
}

document.getElementById('write')?.addEventListener('click', () => {
    bytes = write(buildSpreadsheet());
    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>odf · Write an .ods from arrays, 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/odf": "/vendor/odf/main.js", "@awacloud/odf/": "/vendor/odf/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Write an .ods from arrays, 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 (hover a cell for its value 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/odf · AGPL-3.0-only</li>
    </ul>
  </footer>
  <!-- aln:end -->
</body>
</html>