Sheets and the workbook JSONSpreadsheet
Work with multiple sheets from the tab bar and the API, and load and save workbooks as plain JSON with WorkbookJSON, SheetJSON and CellJSON.
A workbook holds one or more sheets. Users manage them from the tab bar below the grid; your code manages them with the API, and saves and loads the whole workbook as a plain JSON object.
The tab bar#
- + adds a sheet at the end.
- Double-click a tab to rename it.
- The tab menu, opened by right-clicking a tab or with
Shift+F10on a focused tab, has Rename, Delete, Duplicate, Tab color…, Hide, Unhide for each hidden sheet, Move left and Move right. - A sheet with a
tabColorshows that colour as the underline of its tab. - With a tab focused, the arrow keys,
HomeandEndswitch sheets,F2renames andDeletedeletes. Ctrl+Page UpandCtrl+Page Downswitch to the previous and next visible sheet.
A workbook always keeps at least one visible sheet, so Delete and Hide are disabled on the last one. Set sheetTabs: false to hide the tab bar, for single-sheet tools.
Sheets in code#
sheet.addSheet('Assumptions', 0);
sheet.renameSheet('Assumptions', 'Rates and terms');
sheet.moveSheet('Rates and terms', 2);
sheet.setSheetHidden('Rates and terms', true);
sheet.setActiveSheet('Loan');
sheet.removeSheet('Scratch');
console.log(sheet.getSheetNames(), sheet.getActiveSheet());| Method | Purpose |
|---|---|
getSheetNames() |
All sheet names in tab order, including hidden ones. |
getActiveSheet() |
The name of the sheet on screen. |
addSheet(name?, index?) |
Adds a sheet and returns its name. Without a name it is called Sheet2, Sheet3 and so on. |
renameSheet(name, newName) |
Renames a sheet and rewrites every formula that refers to it. |
moveSheet(name, index) |
Moves a sheet to a position in the tab order. |
setSheetHidden(name, hidden) |
Hides or shows a sheet. Hidden sheets still calculate, and formulas can refer to them. |
setActiveSheet(name) |
Shows a sheet. |
removeSheet(name) |
Deletes a sheet. Formulas that referred to it show #REF!. |
duplicateSheet(name, newName?) |
Copies a sheet, puts the copy right after it and returns the new name. Without a name the copy is called Name (2). |
setTabColor(name, color) |
Sets the tab colour to a hex colour, or removes it with null. |
getSheetView(sheet?), setSheetView(view, sheet?) |
Read and change the sheet view. |
Sheet names are up to 31 characters, cannot contain \ / ? * [ ] :, cannot start or end with an apostrophe, and must be unique. addSheet() and renameSheet() throw an error for a name that breaks these rules.
Cell methods such as getValue() and setRange() work on any sheet when the address has a sheet prefix: sheet.setValue("'Rates and terms'!B2", 0.059). Structure methods, such as insertRows(), setFreeze() and setColumnWidth(), apply to the active sheet.
Every change fires sheetChange with the sheet name, an action of activate, add, remove, rename, move, hide or show, and for renames the previous name. Sheet operations are undoable.
Duplicating a sheet#
The copy has the cells, formatting, sizes, view and objects of the original. Tables and pivot tables in the copy get a _2 suffix because their names must be unique, and structured references inside the copy point to the renamed tables. Charts, pictures, shapes and slicers get new ids. Parts of an imported Excel file that are kept only for export (preserved) stay with the original and are not copied. Duplicating is one undo step and fires sheetChange with the action add.
Hidden and very hidden sheets#
A hidden sheet (hidden: true) is offered under Unhide in the tab menu. A very hidden sheet (hidden: true, veryHidden: true), as set from VBA in Excel, is never offered there. setSheetHidden(name, false) shows either kind and clears veryHidden.
Sheet views#
SheetJSON.view holds how a sheet is shown. It is applied when the workbook loads and written back by toJSON() and exportXlsx().
| Property | Behaviour |
|---|---|
zoom |
Zoom of this sheet in percent. A sheet without its own zoom uses the zoom option or the last zoom that was set. setZoom() and the zoom controls write the zoom of the active sheet, and zoomChange also fires when a sheet with a different zoom is activated. |
gridlines, headings |
Show or hide gridlines and the row and column headings for this sheet. They override the gridlines and headings options. The View tab toggles write them, and update({ gridlines }) or update({ headings }) removes the override of the active sheet. |
rightToLeft |
Lays the sheet out from the right. While such a sheet is active the whole component, ribbon included, is mirrored. Numbers stay right-aligned. |
showZeros |
false shows cells with the value 0 as empty, on screen and in print. View > Zero values toggles it. |
activeCell, selection |
Restored the first time the sheet is activated. toJSON() writes the current ones once the selection has moved, or when the loaded view already had them. selection is a space-separated list of ranges. |
topLeftCell |
The scroll position, restored the first time the sheet is activated. |
split |
A split window from Excel. See below. |
showFormulas, mode |
Kept and exported, not applied. |
sheet.setSheetView({ zoom: 125, gridlines: false, showZeros: false });
sheet.setSheetView({ gridlines: undefined }); // back to the option
sheet.getSheetView('Loan'); // { zoom: 125, showZeros: false }A key set to undefined is removed from the view.
Split panes#
A split divides the grid into two or four panes that show the same sheet and scroll on their own. With a horizontal bar the top and bottom panes share the horizontal position and each has its own vertical position; a vertical bar does the same for left and right.
sheet.splitPanes('D12'); // bars above row 12 and left of column D
sheet.splitPanes(); // at the active cell
sheet.removeSplit();- View > Split toggles a split at the active cell. A cell in the first visible row or column gives one bar, and the first visible cell splits the grid through the middle.
- Drag a bar to move it. Drag it to the edge of the grid, or double-click it, to remove it.
Escapecancels a drag. - A bar is a focusable separator: the arrow keys move it by one row or column, and
Delete,BackspaceorHomeremoves it. F6andShift+F6move the active cell from pane to pane before going on to the other regions of the component. Clicking a pane makes it the active one.- Freeze panes and a split exclude each other on a sheet: setting one clears the other. Setting, moving and removing a split are undo steps.
- The split is stored in
view.split(xandyin twentieths of a point,topLeftCellof the bottom-right pane andactivePane), as in xlsx files, and is written back.
Selection, editing, merged cells and conditional formats work in every pane. Pictures, charts, shapes, slicers, note and comment markers, table and filter buttons and auditing arrows are drawn in the bottom-right pane only. The top and left panes scroll with the wheel, a trackpad and the keyboard; they have no scrollbars and do not scroll by touch dragging. The scroll positions of the panes are not saved.
Workbook view. WorkbookJSON.activeSheet is the sheet shown first, when it is visible. WorkbookJSON.view.showSheetTabs: false hides the tab bar, like the sheetTabs option.
Named sheet views#
A named view is a second way of looking at one sheet: its own filter, its own hidden rows and its own sort indicator. It lets one person filter a shared sheet without changing what the others see. View > Sheet view lists Default view and the named views of the active sheet, with Save view… and, inside a view, Delete view.
| Action | What happens |
|---|---|
| Save view… | Stores the filter, hidden rows and sort indicator that are on screen under a name, and makes that view the active one. Saving under an existing name replaces it. One undo step. |
| Choose a named view | The default view is put aside and the view's filter and hidden rows are shown. |
| Filter or hide rows inside a view | Changes this view only. The default view, and everyone else's rows, stay as they were. |
| Choose Default view | Your changes are stored in the view you leave, and the default view comes back as it is now, including what others changed in it meanwhile. |
sheet.saveSheetView('Laptops'); // returns the stored name, or undefined when read-only
sheet.setColumnFilter('B', { kind: 'values', values: ['Laptops'] });
sheet.getSheetViews(); // [{ name: 'Laptops', active: true }]
sheet.applySheetView(null); // back to the default view
sheet.applySheetView('Laptops');
sheet.deleteSheetView('Laptops');toJSON() writes the views to SheetJSON.views and always writes the default view to hiddenRows and autoFilter, whichever view is on screen, so a saved workbook opens in its default view. Which view you are in is not saved.
With collaboration, the list of views is shared and the view each person is in is not. A filter made inside a view sends nothing; the stored view is sent to the others when you save it or leave it.
Limits:
- A view does not reorder rows. Sorting inside a view sorts the cells, for everyone, as it does outside a view; the view remembers which column carries the sort arrow.
- Hidden columns, the filters of tables, zoom and frozen panes are not part of a view.
- Views are kept in the workbook JSON. They are not written to xlsx, and the sheet views Excel for the web stores in a file are not read.
- Rows inserted or deleted while a view is not on screen do not move the row numbers stored in it.
Cross-sheet formulas#
Refer to another sheet with its name and an exclamation mark: =SUM(Sales!D2:D500), or with quotes when the name contains spaces: ='Rates and terms'!B2. Hidden sheets are a good place for lookup tables and assumptions that users should not edit directly. See References.
The workbook JSON#
toJSON() returns the whole workbook as a JSON-serializable WorkbookJSON; fromJSON(json), the data option and update({ data }) load one. Store it in your database, send it to the headless engine on a server, or convert it to an xlsx file.
const json = sheet.toJSON();
await fetch('/api/models/loan-2026', { method: 'PUT', body: JSON.stringify(json) });
const saved = (await (await fetch('/api/models/loan-2026')).json()) as WorkbookJSON;
sheet.fromJSON(saved);Loading a workbook replaces the current one and clears the undo history.
WorkbookJSON#
version is always 1. activeSheet names the sheet to show first. names holds defined names, optionally scoped to a sheet. settings stores iterative calculation, which the iterativeCalculation option overrides.
SheetJSON#
| Property | Content |
|---|---|
cells |
Cells keyed by A1 address, such as { B4: { formula: '=PMT(...)', value: 1539.29 } }. Only non-empty cells are listed. |
columnWidths, rowHeights |
Pixel sizes keyed by column letter and by 1-based row number, only for columns and rows that differ from the default. Every exporter and importer, including xlsx, ods and toJSON(), uses these keys. On input a columnWidths key made of digits is also accepted and read as a 0-based column index. |
hiddenRows, hiddenColumns |
1-based row and column numbers. |
merges |
Merged ranges, such as ['A1:E1']. |
freeze |
{ rows, columns } frozen at the top and left. |
conditionalFormats, validations |
Conditional formats and validation rules. |
autoFilter |
The autofilter range, the values shown per column and, for conditions that are not value lists, the criteria per column. |
comments |
Threaded comments by cell address, each with its replies. |
hidden, veryHidden, tabColor |
Whether the sheet is hidden or very hidden, and its tab colour. |
view |
The sheet view: zoom, gridlines, headings, direction, selection and split. |
sortState |
The last sort of the autofilter range, shown as an arrow on the filter button. Tables carry their own sortState. |
CellJSON#
A cell has a value, a formula, a style, or a combination:
{
"A1": { "value": "Principal" },
"B1": { "value": 250000, "style": { "numberFormat": "#,##0.00" } },
"B4": { "formula": "=PMT(B2/12, B3*12, -B1)", "value": 1539.293001065986 },
"C9": { "formula": "=1/0", "value": { "error": "#DIV/0!" } }
}- Values are numbers, strings, booleans or errors written as
{ "error": "#N/A" }. Dates and times are serial numbers with a date format; usedateToSerial()to produce them. - For formula cells,
valueis the cached result from the last calculation. When loading, formulas are recalculated, so the cached value only matters to tools that read the JSON without the engine. - A dynamic array formula is stored on its anchor cell only; its spilled results are recalculated after loading.
Defined names and the Name Manager#
defineName(name, formula, sheet?) adds a workbook-level name, or a sheet-level name when you pass a sheet. getNames() lists the names and removeName(name, sheet?) deletes one. Names can be used anywhere a reference can, including SUM(FirstQuarter) and the name box.
sheet.defineName('TaxRate', '=Settings!$B$2');
sheet.getNames(); // [{ name: 'TaxRate', formula: '=Settings!$B$2' }]Ctrl + F3 or openDialog('nameManager') opens the Name Manager. It lists every name with what it refers to and its scope, and lets users add, edit and delete names. It rejects names that look like cell references, contain spaces or repeat a name in the same scope. Every change can be undone.
Watching for changes#
To keep a server copy in sync, save after changes settle:
let pending: ReturnType<typeof setTimeout> | undefined;
const save = () => {
clearTimeout(pending);
pending = setTimeout(() => saveModel(sheet.toJSON()), 1500);
};
sheet.on('cellChange', save);
sheet.on('sheetChange', save);cellChange fires for every changed cell, with the old and new value, the formula and a source: edit, api, paste, fill, undo, redo, replace, clear or sort. Cells that change only because a formula recalculated do not fire cellChange; the recalculated event reports those.