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

    Class Worksheet

    Represents a single worksheet within a workbook.

    Provides access to cells, rows, columns, merge ranges, charts, pivot tables, comments, hyperlinks, page setup, and other sheet-level features.

    const ws = wb.addSheet('Data');
    ws.cell('A1').value = 'Name';
    ws.cell('B1').value = 'Score';
    ws.frozenPane = { rows: 1, cols: 0 };
    Index
    • get name(): string

      Returns the sheet tab name.

      Returns string

    • set name(value: string): void

      Renames the sheet tab, validated against Excel's sheet-name rules: 1-31 UTF-16 code units, none of \ / * ? [ ] : and no control character (Unicode Cc), no leading or trailing apostrophe, and not History in any case.

      On a sheet that belongs to a workbook this is Workbook.renameSheet: the name must be unique ignoring case and canonical equivalence, and defined names that refer to the sheet are rewritten. A standalone worksheet only validates the name.

      Parameters

      • value: string

      Returns void

      ModernXlsxError with code INVALID_ARGUMENT if the name is empty, exceeds 31 UTF-16 code units, contains forbidden characters, starts or ends with an apostrophe, is the reserved name History (any case), or is already used by another sheet of the workbook (any case or normal form); nothing is changed then.

    • Adds a chart to this worksheet using a builder callback.

      Parameters

      • type: ChartType

        The chart type (e.g., 'bar', 'line', 'pie', 'scatter').

      • configure: (builder: ChartBuilder) => void

        A callback that receives a ChartBuilder for fluent configuration.

      Returns void

      When the built chart fails validateChartData (a value outside its ECMA-376 range, a colour that is not RRGGBB, two series sharing an order, an anchor that ends before it starts, an empty series reference) or its secondary chart has a secondary chart of its own.

      ws.addChart('bar', (b) => {
      b.title('Sales')
      .addSeries({ valRef: 'Sheet1!$B$2:$B$5' })
      .legend('bottom');
      });
    • Adds a manual column page break with id set to col and max 1048575. ECMA-376 places a column break left of the zero-based column id, so the break falls to the right of the 1-based column col.

      Parameters

      • col: number

        The break id: the 1-based number of the last column left of the break.

      Returns void

    • Adds a comment to the given cell reference.

      Parameters

      • cellRef: string

        The cell reference (e.g., 'A1').

      • author: string

        The comment author name.

      • text: string

        The comment text.

      Returns void

      ws.addComment('A1', 'Alice', 'Please review this value');
      
    • Adds a hyperlink to a cell. A value that starts with a URI scheme (/^[A-Za-z][A-Za-z0-9+.-]*:/: https:, mailto:, file:, and also a drive path such as C:\book.xlsx) is stored as the external target, written as a sheet relationship with TargetMode="External"; anything else, including a same-sheet range such as 'A1:B2' or 'B:D', is an in-workbook location such as 'Sheet2!A1' or a defined name.

      Parameters

      • cellRef: string

        The cell reference to attach the hyperlink to (e.g., 'A1').

      • location: string

        External URL, mailto: address or file, or an in-workbook reference (e.g., 'https://example.com' or 'Sheet2!A1').

      • Optionalopts: { display?: string; tooltip?: string }

        Optional display text and tooltip.

      Returns void

      ws.addHyperlink('A1', 'https://example.com', {
      display: 'Visit Site',
      tooltip: 'Opens example.com',
      });
      ws.addHyperlink('A2', 'Sheet2!A1', { display: 'Go to Sheet2' });
    • Adds a pivot table definition to this sheet. Its cacheId must name a pivot cache of the workbook, such as one added with Workbook.addPivotCache (the write fails otherwise). A row, column or page field with empty items is completed from that cache on write, and the cache then refreshes when Excel opens the file (see PivotTableData).

      Parameters

      Returns void

    • Adds a manual row page break with id set to row and max 16383. ECMA-376 places a row break above the zero-based row id, so the break falls below the 1-based row row.

      Parameters

      • row: number

        The break id: the 1-based number of the last row above the break.

      Returns void

    • Adds a table definition to the sheet.

      The displayName must be a name Excel opens: 1 to 255 UTF-16 code units; no space, tab, line break, DEL or ASCII punctuation other than _, ., \ and ?; not starting with a digit, ., ? or a combining mark (Unicode M; Excel refused U+0301 + abc and U+093F + x, while a + U+0301 + bc opens; a leading Thai mark such as U+0E34 + a, which Excel opens, is refused too); not TRUE or FALSE; not a cell reference in the grid (T2, xfd1; XFE1 and A0 are fine); and not an R1C1 reference or a name that starts with one (R, C, RC, R1x, C1_, RC2x; a . right after the number, as in R1.a, is fine). Case is ignored. It must also differ, ignoring case and canonical equivalence, from the display name of every other table and from every defined name in the workbook. An explicit name may be at most 255 code units and must differ, compared the same way, from every other table's explicit name.

      With totalsRowCount 1, Excel keeps a table's totals as ordinary cells in the last row of its range, so this method also writes them: for each column with a totalsRowFunction ('sum', 'average', 'count', 'countNums', 'max', 'min', 'stdDev' or 'var') the SUBTOTAL formula Excel writes (SUBTOTAL(109,Table1[Amount]) for 'sum'), for 'custom' the column's totalsRowFormula, and for a column with a totalsRowLabel and no function the label text. The formulas have no cached value, so Excel computes them when it opens the file. A table read from a file is not changed.

      A totals cell that already holds a value or a formula is kept as it is, and Excel opens the file only if the kept cell agrees with its column (Excel 365 probes):

      • a SUBTOTAL column: a plain value (number, text, boolean), or the formula above, which Excel also takes without the table name (SUBTOTAL(109,[Amount])) and with the function or column name in another case; any other formula is refused, the table name in another case and a space inside the parentheses included;
      • a 'custom' column with a totalsRowFormula: any formula; a value or an empty cell is refused (without a totalsRowFormula, anything opens);
      • a column with a totalsRowLabel and no function (or 'none'): the label text, exactly, or nothing; other text, a number, a boolean or a formula is refused;
      • a column with neither: text or nothing; a number, a boolean or a formula is refused.

      Workbook.validate() reports a totals cell Excel refuses as an error.

      A column's calculatedColumnFormula and totalsRowFormula are stored in the form Excel writes in a file, which has no @ this-row shorthand: Excel refuses to open a table definition holding [@Qty], [@[Unit Cost]], Table1[@Qty] or [@] (outside a string literal); write Table1[[#This Row],[Qty]], Table1[[#This Row],[Unit Cost]] or Table1[#This Row] there. [Qty] and [[#This Row],[Qty]] without the table name open. A [@...] that names a column of its table, ignoring case, is a whole-column reference and opens: Excel writes the column @Home of table AtT as AtT[@Home] (the names compared after their _xHHHH_ escapes are decoded). A [@...] of a table in another workbook, which Excel stores as [1]!Ext[@Home], is not checked. The formulas are kept as given.

      Parameters

      Returns void

      ModernXlsxError with code INVALID_ARGUMENT if the display name or the name breaks one of the rules above (duplicates are found ignoring case and canonical equivalence: café with U+00E9 repeats cafe + U+0301), or a calculatedColumnFormula or totalsRowFormula uses the @ shorthand (the message gives the form to write instead); the sheet is unchanged then.

    • Adds a threaded comment to the given cell reference: the root of a new thread. A cell holds one thread (Excel shows only the first thread on a cell and drops the rest), so a cell that already has a thread root throws; add to that thread with Worksheet.replyToComment instead. Creates a person entry in the workbook if the author does not exist yet.

      The comment and person ids are upper-case GUIDs in braces ({XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}), the form Excel requires. On write the sheet also gets the legacy placeholder note Excel needs to show the thread (author tc={id}, text [Threaded comment] ... Comment: and the replies), with its hidden note shape. It is added to the file only, not to Worksheet.comments, and only when the cell has no note: a note already on the cell is written as it is, and Excel then shows that note, not the thread. A read of the file returns the placeholder in Worksheet.comments, as it does for a file Excel saved, and later writes keep it as it is.

      The comment's timestamp is the current time as an ISO 8601 UTC string (new Date().toISOString() form). The writer writes it as dT in the form Excel reads (UTC, hundredths of a second, no Z); a read returns dT as the file holds it.

      Parameters

      • cell: string

        The cell reference (e.g., 'A1'); it is stored without $ and in upper case ('$d$4' becomes 'D4'), and cells are compared that way ('a1', '$A$1' and 'A1' are one cell).

      • text: string

        The comment text: at most 32,767 UTF-16 code units (its length; an astral character such as an emoji counts as two). Excel refuses a file with a longer threaded comment.

      • author: string

        The display name of the author.

      Returns string

      The ID of the created comment, an upper-case GUID in braces.

      ModernXlsxError with code INVALID_ARGUMENT, leaving the worksheet unchanged, if the cell already has a thread root (the message names the cell and the root's ID to pass to replyToComment), if text is longer than 32,767 UTF-16 code units, or on a worksheet that was not obtained from a workbook.

      const id = ws.addThreadedComment('A1', 'Looks good!', 'Alice');
      ws.replyToComment(id, 'Thanks!', 'Bob');
    • Adds a data validation rule to the given cell range reference.

      Parameters

      • ref: string

        The cell range to validate (e.g., 'B2:B100').

      • rule: Omit<DataValidationData, "sqref">

        The validation rule: validationType, operator, formula1, formula2, allowBlank, showErrorMessage, errorTitle and errorMessage (each null when unused), plus the optional showInputMessage, promptTitle and prompt.

      Returns void

      ws.addValidation('B2:B100', {
      validationType: 'list',
      operator: null,
      formula1: '"Yes,No,Maybe"',
      formula2: null,
      allowBlank: true,
      showErrorMessage: true,
      errorTitle: null,
      errorMessage: null,
      });
    • Returns the cell at the given A1-style reference, creating the row and cell if needed. The returned Cell is a live wrapper -- mutations are reflected in the underlying sheet data.

      Parameters

      • ref: string

        A1-style cell reference (e.g., 'B3', 'AA100').

      Returns Cell

      A mutable Cell wrapper.

      ModernXlsxError with code INVALID_CELL_REF if ref is not an uppercase A1 reference within A1:XFD1048576.

      const cell = ws.cell('B3');
      cell.value = 42;
      cell.formula = 'A3*2';
    • Collapses grouped rows: hides each row in the range that has an outline level and marks the summary row collapsed. The summary row is the row after the range, or the row before it when outlineProperties.summaryBelow is false.

      Parameters

      • startRow: number

        1-based start row index (inclusive).

      • endRow: number

        1-based end row index (inclusive).

      Returns void

    • Groups columns by setting their outline level (1-7), creating missing column definitions.

      Parameters

      • startCol: number

        1-based start column index (inclusive).

      • endCol: number

        1-based end column index (inclusive).

      • level: number = 1

        Outline level, clamped to 0-7; 0 clears the level. Defaults to 1.

      Returns void

      ModernXlsxError with code INVALID_ARGUMENT, before any column changes, if startCol or endCol is not an integer from 1 to 16384.

    • Groups rows by setting their outline level (1-7), creating missing rows.

      Parameters

      • startRow: number

        1-based start row index (inclusive).

      • endRow: number

        1-based end row index (inclusive).

      • level: number = 1

        Outline level, clamped to 0-7; 0 clears the level. Defaults to 1.

      Returns void

      ModernXlsxError with code INVALID_ARGUMENT, before any row changes, if startRow or endRow is not an integer from 1 to 1048576.

    • Replies to an existing threaded comment. Creates a person entry in the workbook if the author does not exist yet.

      The reply's parentId is the thread root: a reply to a reply joins its thread root, as Excel does (Excel refuses a file whose reply names another reply as its parent).

      Excel shows a thread's replies in the order of their timestamps (dT, which it keeps to the hundredth of a second). The reply's timestamp is the current time as an ISO 8601 UTC string, or, when that is not at least 10 ms after the latest timestamp already in the thread (replies added within the same hundredth, or a thread stamped ahead of this clock), that latest timestamp plus 10 ms, so replies show in the order they were added. A timestamp without a zone, as Excel writes dT, is UTC.

      Parameters

      • commentId: string

        The ID of the comment to reply to (a thread root or a reply), exactly as Worksheet.addThreadedComment or Worksheet.replyToComment returned it or the file holds it.

      • text: string

        The reply text: at most 32,767 UTF-16 code units (its length; an astral character such as an emoji counts as two). Excel refuses a file with a longer threaded comment.

      • author: string

        The display name of the reply author.

      Returns string

      The ID of the reply comment, an upper-case GUID in braces.

      ModernXlsxError with code COMMENT_NOT_FOUND if no threaded comment on this sheet has the ID, or INVALID_ARGUMENT, leaving the worksheet unchanged, if text is longer than 32,767 UTF-16 code units or on a worksheet that was not obtained from a workbook.

    • Sets the width of a single 1-based column, creating or updating its definition.

      Parameters

      • col: number

        The 1-based column index.

      • width: number

        The column width in Excel character units.

      Returns void

      ModernXlsxError with code INVALID_ARGUMENT if col is not an integer from 1 to 16384.

      ws.setColumnWidth(1, 20); // column A = 20 chars wide
      
    • Sets the print area for this sheet via a _xlnm.Print_Area defined name. Does nothing on a worksheet that does not belong to a workbook.

      Excel refuses a file whose print area has no sheet qualifier, so every comma-separated area of ref that lacks one ("A1:B2") is stored qualified with this 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

      • ref: 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 ref is not a reference or a comma-separated list of references.

    • Sets the height (in points) of the given 1-based row, creating it if needed. The height is written as a custom height (customHeight="1"), so Excel shows it instead of sizing the row to its content.

      Parameters

      • rowIndex: number

        The 1-based row index.

      • height: number

        Row height in points (e.g., 24 for double-height).

      Returns void

      ModernXlsxError with code INVALID_ARGUMENT if rowIndex is not an integer from 1 to 1048576.

      ws.setRowHeight(1, 30); // set header row to 30pt
      
    • Sets the visibility of the given 1-based row, creating it if needed.

      Parameters

      • rowIndex: number

        The 1-based row index.

      • hidden: boolean

        true to hide the row, false to show it.

      Returns void

      ModernXlsxError with code INVALID_ARGUMENT if rowIndex is not an integer from 1 to 1048576.