modern-xlsx API Reference - v1.3.0
    Preparing search index...

    Class Workbook

    Represents an Excel workbook containing sheets, styles, and metadata.

    This is the root object for reading, writing, and manipulating XLSX files. Obtain an instance via readBuffer, readFile, or construct a new empty workbook with new Workbook(). Its WASM-backed methods use the full build, which supports password-protected files.

    const wb = new Workbook();
    const ws = wb.addSheet('Data');
    ws.cell('A1').value = 'Hello';
    const bytes = await wb.toBuffer();

    Hierarchy

    • Workbook
      • Workbook
    Index
    loader: WasmLoader = loader

    The WASM build an entry subclass binds; unset on the base.

    • Generate a barcode and embed it as an image anchored to the given cell range.

      Parameters

      • sheetName: string

        Target sheet name.

      • anchor: ImageAnchor

        Cell range to anchor the barcode image to, as 0-based column and row indexes (fromCol, fromRow, toCol, toRow).

      • value: string

        Data to encode in the barcode.

      • options: DrawBarcodeOptions

        Barcode type, rendering, and sizing options.

      Returns void

      If the anchor is invalid (see Workbook.addImage) or a rendering option is out of range (see generateBarcode).

      // Cells A1 to C5: 0-based column and row indexes.
      wb.addBarcode('Sheet1', { fromCol: 0, fromRow: 0, toCol: 2, toRow: 4 }, '12345', {
      type: 'code128',
      });
    • Adds an image (PNG, JPEG or GIF bytes, matching format) anchored to a cell range on the given sheet. The image is embedded via preservedEntries and OOXML drawing XML.

      Parameters

      • sheetName: string

        Target sheet name.

      • anchor: ImageAnchor

        Cell range to anchor the image to, as 0-based column and row indexes (fromCol, fromRow, toCol, toRow).

      • imageBytes: Uint8Array

        Raw image bytes.

      • format: "png" | "jpeg" | "gif" = 'png'

        Image format extension (default: 'png').

      Returns void

      ModernXlsxError with code SHEET_NOT_FOUND if no sheet has the exact name sheetName.

      If an anchor column is not an integer 0-16383, a row is not an integer 0-1048575, an offset is not a non-negative safe integer, or the anchor ends before it starts; the workbook is left unchanged.

      const png = fs.readFileSync('logo.png');
      // Cells B2 to E10: 0-based column and row indexes.
      wb.addImage('Sheet1', { fromCol: 1, fromRow: 1, toCol: 4, toRow: 9 }, png);
    • Adds a named range. If sheetId is provided, the name is scoped to that sheet.

      Parameters

      • name: string

        The defined name (e.g., 'TotalSales'): 1-255 characters, starting with a letter, _ or \, then letters, combining marks (the vowel signs of Thai and Indic scripts, Arabic harakat, Hebrew points, decomposed accents), digits, _, ., `` or ?; not TRUE or FALSE; not a cell reference inside the grid (A1, T2; XFE1 and A0 are fine); not an R1C1 reference or a name that starts with one (R, C, R1C1, R1x, C1_total, R2D2; a . right after the number, as in R1.a, is fine); and, ignoring case and canonical equivalence (café with U+00E9 is cafe + U+0301), not the display name of a table on any sheet. Worksheet.addTable applies the same reference rules to a table name, whose characters may also be symbols such as € that a defined name may not hold. The _xlnm. prefix is accepted only for Print_Area, Print_Titles and _FilterDatabase. Excel matches built-in names without regard to letter case, so _xlnm.Print_Area and _xlnm.Print_Titles in any case ('_xlnm.print_area') are stored in the spelling Excel writes, _xlnm.Print_Area and _xlnm.Print_Titles, and the print-area and print-titles getters and setters see them.

      • value: string

        The range reference (e.g., 'Sheet1!$A$1:$A$10'). For _xlnm.Print_Area and _xlnm.Print_Titles (in any letter case) with a sheetId, an area without a sheet prefix is stored qualified with that sheet's name.

      • OptionalsheetId: number

        Optional zero-based sheet index to scope the name to.

      Returns void

      ModernXlsxError with code INVALID_ARGUMENT if the name breaks those rules, sheetId is not a sheet index of this workbook, the name (ignoring case and canonical equivalence) already exists in the same scope or names a table, or the value of a built-in print name with a sheetId is not a comma-separated list of references.

      wb.addNamedRange('Revenue', 'Sheet1!$B$2:$B$100');
      
    • Adds a new empty sheet to the workbook and returns it. The name is validated against Excel's sheet-name rules (see Worksheet.name).

      Parameters

      • name: string

        The sheet tab name. Must be 1-31 UTF-16 code units, free of \ / * ? [ ] : and control characters, not start or end with an apostrophe, and be unique ignoring case and canonical equivalence (café with U+00E9 and cafe + U+0301 are one name); History is reserved in any case.

      Returns Worksheet

      The newly created Worksheet.

      ModernXlsxError with code INVALID_ARGUMENT if the name is invalid or reserved, or a sheet with that name (in any case or normal form) already exists.

      const ws = wb.addSheet('Q1 Report');
      ws.cell('A1').value = 'Revenue';
      ws.cell('B1').value = 50000;
    • Clones a sheet and inserts the copy at the end (or given position).

      The copy's tables get new workbook-unique ids and names (Sales becomes Sales_2, or the next free suffix; a source name too long for the suffix is cut so the new name stays within Excel's 255 UTF-16 units, never inside a surrogate pair, and a cut name that would read as a cell or R1C1 reference gets a leading _), and its threaded comments get new ids (upper-case GUIDs in braces, the form Excel requires) with replies and legacy tc= comment authors still pointing at them. Inserting before an existing sheet shifts later sheet-scoped names and workbook views, and drops the calculation chain.

      Structured references to a renamed table (Sales[Amount], matched ignoring case and canonical equivalence, and names such as a\b, a?b or Ventes€ the formula tokenizer cannot scan) are rewritten to the new name in the copy only: in every cell formula of the copy (its totals row included) and in the calculatedColumnFormula and totalsRowFormula of its tables. Text in string literals, references to tables on other sheets, formulas on other sheets or in defined names that name the source table, and a whole formula the tokenizer rejects for a reason other than a table name (a sheet-qualified Data!Sales[Amount], an unclosed string, or another name it cannot scan, such as a defined name \rate) keep naming the source table.

      Parameters

      • sourceIndex: number

        Zero-based index of the sheet to clone.

      • newName: string

        Tab name for the cloned sheet (unique ignoring case and canonical equivalence).

      • OptionalinsertIndex: number

        Optional zero-based position for the clone, from 0 to the sheet count; defaults to the end.

      Returns Worksheet

      The newly created Worksheet (deep copy of the source).

      ModernXlsxError with code INVALID_ARGUMENT if either index is invalid, or the new name is invalid, reserved or already taken.

      const copy = wb.cloneSheet(0, 'Sheet1 Copy');
      
    • Gets the print titles (repeat rows/columns) for the given sheet.

      Parameters

      • sheetIndex: number

        0-based sheet index.

      Returns string | null

      The defined name value (e.g., "Sheet1!$1:$2,Sheet1!$A:$B") or null.

    • Returns the worksheet with the given name, or undefined if not found. The lookup is case-sensitive.

      Parameters

      • name: string

        The sheet tab name to look up, matched exactly.

      Returns Worksheet | undefined

      The matching Worksheet, or undefined.

      const ws = wb.getSheet('Sales');
      if (ws) console.log(ws.cell('A1').value);
    • Hides a sheet. At least one sheet must remain visible.

      Parameters

      • nameOrIndex: string | number

        The sheet name or zero-based index to hide.

      Returns void

      ModernXlsxError with code SHEET_NOT_FOUND if the sheet is not found, or INVALID_ARGUMENT if it is the last visible sheet.

      wb.hideSheet('Internal');
      
    • Moves a sheet from one position to another.

      Sheet-scoped defined names and the workbook views' activeTab/firstSheet follow their sheets. A real move (fromIndex !== toIndex) drops the calculation chain, which Excel rebuilds.

      Parameters

      • fromIndex: number

        Zero-based source position.

      • toIndex: number

        Zero-based target position.

      Returns void

      ModernXlsxError with code INVALID_ARGUMENT if either index is not an integer in range.

      wb.moveSheet(2, 0); // move third sheet to first position
      
    • Removes a sheet by name or 0-based index.

      Defined names scoped to the removed sheet are dropped, later sheets' scoped names and the workbook views' activeTab/firstSheet follow their sheets, and the calculation chain is dropped (Excel rebuilds it).

      Parameters

      • nameOrIndex: string | number

        The sheet name or zero-based index to remove.

      Returns boolean

      true if the sheet was removed, false if not found.

      wb.removeSheet('OldSheet');
      wb.removeSheet(2);
    • Renames a sheet and rewrites the defined names that refer to it.

      Every defined-name value (print areas and print titles included) has its sheet prefixes that name the old sheet, quoted or not and compared ignoring case (final sigma folded; U+0130 is not matched by i + U+0307), not canonical equivalence, replaced with the new name, quoted when needed, as Excel's own rename stores them: Data!$A$1 becomes 'My Data'!$A$1, and an end of a 3-D span is rewritten too (Data:Data3!A1 becomes 'My Data:Data3'!A1; renaming a sheet between the ends changes nothing). A prefix with a colon is a span only when both ends name sheets of the workbook (compared the same way, before the rename). Otherwise only a quoted one is a path into another workbook, which Excel's own rename keeps, and so does this one: 'C:/dir/Book.xlsx'!A1 and 'C:Nosuch'!A1 are kept when sheet C is renamed and no sheet Nosuch exists. An unquoted one whose first end is no sheet is a name, the range operator and a sheet-qualified reference, and its last end follows the rename as in Excel: First:Data!$C$10 becomes First:'My Data'!$C$10, while SUM(Data:Nosuch!$A$1) is kept. A sheet name right after the range operator is written quoted, as Excel 365 stores it (2026-11-14): renaming Data to First turns First:Data!$C$10 and First:'Data'!$C$10 into First:'First'!$C$10 (unquoted, the text would be the one-sheet span First:First), and renaming Sheet3 to First turns First:Sheet1!$C$10 into First:'Sheet1'!$C$10. A name and a sheet spelled alike are told apart by those quotes alone, in Excel too: hand-written First:First!$C$10 is a span. A prefix spelled in another normal form (cafe + U+0301 for a sheet café with U+00E9) is kept, as Excel 365's own rename keeps it (2026-11-13): Excel does not take it for the sheet. A reference into another workbook ([1]Data!$A$1, the form Excel stores) keeps naming that workbook's sheet, as do text in string literals and a longer sheet name (Data10). A value the formula tokenizer rejects is left unchanged as a whole, among them one with a sheet-qualified defined name such as Data!Rate, which Excel rewrites. Cell formulas, chart series, pivot cache sources, data validations, conditional formats and hyperlinks are not rewritten. Only values change: the names themselves are kept as they are and not checked, so a name read from a file that addNamedRange would refuse (a€b) does not stop the rename.

      Parameters

      • nameOrIndex: string | number

        The current sheet name or zero-based index.

      • newName: string

        The new tab name (validated against Excel's sheet-name rules, unique ignoring case and canonical equivalence; a rename of the same sheet to another case or normal form of its name is allowed).

      Returns void

      ModernXlsxError with code SHEET_NOT_FOUND if the sheet is not found, or INVALID_ARGUMENT if the new name is invalid, reserved or taken by another sheet (nothing is changed then).

      wb.renameSheet('Sheet1', 'January');
      
    • Validate and auto-repair the workbook. Fixes the repairable issues the validator reports: invalid and duplicate sheet names, missing default styles and dangling style ids, shared-string cells without a value, a missing theme, malformed document-property dates and whitespace-only document-property text fields, row order, and reversed merge ranges. This workbook itself is left unchanged.

      Returns { repairCount: number; report: ValidationReport; workbook: Workbook }

      An object containing the repaired Workbook (an instance of this workbook's class), a validation report, and the number of repairs made.

      const { workbook, repairCount } = wb.repair();
      console.log(`${repairCount} issues repaired`);
    • Sets the print area for the given sheet.

      Excel refuses a file whose print area has no sheet qualifier, so every comma-separated area of value that lacks one ("A1:B2") is stored qualified with the sheet's name, quoted when needed ("'My Sheet'!A1:B2"), and otherwise as written; a qualified area ("Sheet1!$A$1:$D$50") is stored as it is.

      Parameters

      • sheetIndex: number

        0-based sheet index.

      • value: string | null

        The reference or comma-separated list of references (cell, range, column span or row span). Pass null to clear.

      Returns void

      ModernXlsxError with code INVALID_ARGUMENT if sheetIndex is not the index of an existing sheet, or value is not a reference or a comma-separated list of references.

    • Sets print titles (repeat rows/columns) for the given sheet.

      Excel refuses a file whose print titles have no sheet qualifier, so every comma-separated area of value that lacks one ("$1:$2") is stored qualified with the sheet's name, quoted when needed, and otherwise as written; a qualified area ("Sheet1!$1:$2") is stored as it is.

      Parameters

      • sheetIndex: number

        0-based sheet index.

      • value: string | null

        The row span, column span or comma-separated list of them (e.g. "$1:$2" for the first 2 rows, "$A:$B,$1:$2"). Pass null to clear.

      Returns void

      ModernXlsxError with code INVALID_ARGUMENT if sheetIndex is not the index of an existing sheet, or value is not a reference or a comma-separated list of references.

    • Serializes the workbook to an XLSX Uint8Array via the WASM writer.

      Parameters

      • Optionaloptions: WriteOptions

        Optional write options. Pass { password: '...' } to encrypt the file with Agile Encryption (AES-256-CBC, SHA-512). An empty string password is treated as "no encryption".

      Returns Promise<Uint8Array<ArrayBuffer>>

      The XLSX file as a Uint8Array backed by its own ArrayBuffer, so it can be passed straight to new Response() or new Blob().

      ModernXlsxError with code WASM_INIT_FAILED if WASM is not initialized, INVALID_ARGUMENT for a password in the modern-xlsx/lite build, INVALID_WORKBOOK for the causes listed with that code in errors.ts, INVALID_CELL_REF for a frozen pane that puts its top-left cell past XFD1048576, INVALID_CELL_VALUE for a sharedString cell without a value or a cellMetadata other than 1 in a workbook without a metadata part, and SIZE_LIMIT when completing pivot tables built in code would pass the pivot item ceilings, the notes the write generates (VML note shapes and threaded-comment placeholders) would pass their ceiling, or an encrypted package stream would pass 2 GiB (the numbers are in the SIZE_LIMIT entry of errors.ts).

      const bytes = await wb.toBuffer();
      await fs.writeFile('output.xlsx', bytes);
    • Write the workbook to a file on disk. Only available in Node.js, Bun, and Deno environments.

      Parameters

      • path: string

        File path to write to.

      • Optionaloptions: WriteOptions

        Optional write options. Pass { password: '...' } to encrypt.

      Returns Promise<void>

      ModernXlsxError with code WASM_INIT_FAILED if WASM is not initialized, INVALID_ARGUMENT for a password in the modern-xlsx/lite build, INVALID_WORKBOOK for the causes listed with that code in errors.ts, INVALID_CELL_REF for a frozen pane that puts its top-left cell past XFD1048576, INVALID_CELL_VALUE for a sharedString cell without a value or a cellMetadata other than 1 in a workbook without a metadata part, SIZE_LIMIT when completing pivot tables built in code would pass the pivot item ceilings, the notes the write generates (VML note shapes and threaded-comment placeholders) would pass their ceiling, or an encrypted package stream would pass 2 GiB (the numbers are in the SIZE_LIMIT entry of errors.ts), and IO_ERROR outside Node.js-compatible runtimes (browsers, workers, the IIFE build).

      await wb.toFile('./report.xlsx');
      await wb.toFile('./secret.xlsx', { password: 's3cret' });
    • Unhides a sheet (sets state to visible).

      Parameters

      • nameOrIndex: string | number

        The sheet name or zero-based index to unhide.

      Returns void

      ModernXlsxError with code SHEET_NOT_FOUND if the sheet is not found.

      wb.unhideSheet('Internal');
      
    • Validate the workbook for OOXML compliance issues. Returns a structured report with errors, warnings, and fix suggestions. The report stores the issues found first, at most 10,000 of them and at most 16 MiB of message and location text; its counts cover every issue, and omittedIssueCount says how many were left out.

      Returns ValidationReport

      A ValidationReport with categorized issues and severity levels.

      const report = wb.validate();
      console.log(report.issues.length, 'issues found');