4.0.0 • Published 2 months ago

jsreport-exceljs v4.0.0

Weekly downloads
1,012
License
MIT
Repository
github
Last release
2 months ago

ExcelJS

Build Status Code Quality: Javascript Total Alerts

Read, manipulate and write spreadsheet data and styles to XLSX and JSON.

Reverse engineered from Excel spreadsheet files as a project.

Translations

Installation

npm install exceljs

New Features!

Contributions

Contributions are very welcome! It helps me know what features are desired or what bugs are causing the most pain.

I have just one request; If you submit a pull request for a bugfix, please add a unit-test or integration-test (in the spec folder) that catches the problem. Even a PR that just has a failing test is fine - I can analyse what the test is doing and fix the code from that.

Note: Please try to avoid modifying the package version in a PR. Versions are updated on release and any change will most likely result in merge collisions.

To be clear, all contributions added to this library will be included in the library's MIT licence.

Contents

Importing

const ExcelJS = require('exceljs');

ES5 Imports

To use the ES5 transpiled code, use the dist/es5 path.

const ExcelJS = require('exceljs/dist/es5');

Note: The ES5 build has an implicit dependency on a number of polyfills which are no longer explicitly added by exceljs. You will need to add "core-js" and "regenerator-runtime" to your dependencies and include the following requires in your code before the exceljs import:

// polyfills required by exceljs
require('core-js/modules/es.promise');
require('core-js/modules/es.object.assign');
require('core-js/modules/es.object.keys');
require('regenerator-runtime/runtime');

// ...

const ExcelJS = require('exceljs/dist/es5');

Browserify

ExcelJS publishes two browserified bundles inside the dist/ folder:

One with implicit dependencies on core-js polyfills...

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.js"></script>
<script src="exceljs.js"></script>

And one without...

<script src="--your-project's-pollyfills-here--"></script>
<script src="exceljs.bare.js"></script>

Interface

Create a Workbook

var workbook = new Excel.Workbook();

Set Workbook Properties

workbook.creator = 'Me';
workbook.lastModifiedBy = 'Her';
workbook.created = new Date(1985, 8, 30);
workbook.modified = new Date();
workbook.lastPrinted = new Date(2016, 9, 27);
// Set workbook dates to 1904 date system
workbook.properties.date1904 = true;

Set Calculation Properties

// Force workbook calculation on load
workbook.calcProperties.fullCalcOnLoad = true;

Workbook Views

The Workbook views controls how many separate windows Excel will open when viewing the workbook.

workbook.views = [
  {
    x: 0, y: 0, width: 10000, height: 20000,
    firstSheet: 0, activeTab: 1, visibility: 'visible'
  }
]

Add a Worksheet

var sheet = workbook.addWorksheet('My Sheet');

Use the second parameter of the addWorksheet function to specify options for the worksheet.

For Example:

// create a sheet with red tab colour
var sheet = workbook.addWorksheet('My Sheet', {properties:{tabColor:{argb:'FFC0000'}}});

// create a sheet where the grid lines are hidden
var sheet = workbook.addWorksheet('My Sheet', {properties: {showGridLines: false}});

// create a sheet with the first row and column frozen
var sheet = workbook.addWorksheet('My Sheet', {views:[{state: 'frozen', xSplit: 1, ySplit:1}]});

Remove a Worksheet

Use the worksheet id to remove the sheet from workbook.

For Example:

// Create a worksheet
var sheet = workbook.addWorksheet('My Sheet');

// Remove the worksheet using worksheet id
workbook.removeWorksheet(sheet.id)

Access Worksheets

// Iterate over all sheets
// Note: workbook.worksheets.forEach will still work but this is better
workbook.eachSheet(function(worksheet, sheetId) {
  // ...
});

// fetch sheet by name
var worksheet = workbook.getWorksheet('My Sheet');

// fetch sheet by id
var worksheet = workbook.getWorksheet(1);

Worksheet State

// make worksheet visible
worksheet.state = 'visible';

// make worksheet hidden
worksheet.state = 'hidden';

// make worksheet hidden from 'hide/unhide' dialog
worksheet.state = 'veryHidden';

Worksheet Properties

Worksheets support a property bucket to allow control over some features of the worksheet.

// create new sheet with properties
var worksheet = workbook.addWorksheet('sheet', {properties:{tabColor:{argb:'FF00FF00'}}});

// create a new sheet writer with properties
var worksheetWriter = workbookWriter.addSheet('sheet', {properties:{outlineLevelCol:1}});

// adjust properties afterwards (not supported by worksheet-writer)
worksheet.properties.outlineLevelCol = 2;
worksheet.properties.defaultRowHeight = 15;

Supported Properties

NameDefaultDescription
tabColorundefinedColor of the tabs
outlineLevelCol0The worksheet column outline level
outlineLevelRow0The worksheet row outline level
defaultRowHeight15Default row height
defaultColWidth(optional)Default column width
dyDescent55TBD

Worksheet Metrics

Some new metrics have been added to Worksheet...

NameDescription
rowCountThe total row size of the document. Equal to the row number of the last row that has values.
actualRowCountA count of the number of rows that have values. If a mid-document row is empty, it will not be included in the count.
columnCountThe total column size of the document. Equal to the maximum cell count from all of the rows
actualColumnCountA count of the number of columns that have values.

Page Setup

All properties that can affect the printing of a sheet are held in a pageSetup object on the sheet.

// create new sheet with pageSetup settings for A4 - landscape
var worksheet =  workbook.addWorksheet('sheet', {
  pageSetup:{paperSize: 9, orientation:'landscape'}
});

// create a new sheet writer with pageSetup settings for fit-to-page
var worksheetWriter = workbookWriter.addSheet('sheet', {
  pageSetup:{fitToPage: true, fitToHeight: 5, fitToWidth: 7}
});

// adjust pageSetup settings afterwards
worksheet.pageSetup.margins = {
  left: 0.7, right: 0.7,
  top: 0.75, bottom: 0.75,
  header: 0.3, footer: 0.3
};

// Set Print Area for a sheet
worksheet.pageSetup.printArea = 'A1:G20';

// Set multiple Print Areas by separating print areas with '&&'
worksheet.pageSetup.printArea = 'A1:G10&&A11:G20';

// Repeat specific rows on every printed page
worksheet.pageSetup.printTitlesRow = '1:3';

// Repeat specific columns on every printed page
worksheet.pageSetup.printTitlesColumn = 'A:C';

Supported pageSetup settings

NameDefaultDescription
marginsWhitespace on the borders of the page. Units are inches.
orientation'portrait'Orientation of the page - i.e. taller (portrait) or wider (landscape)
horizontalDpi4294967295Horizontal Dots per Inch. Default value is -1
verticalDpi4294967295Vertical Dots per Inch. Default value is -1
fitToPageWhether to use fitToWidth and fitToHeight or scale settings. Default is based on presence of these settings in the pageSetup object - if both are present, scale wins (i.e. default will be false)
pageOrder'downThenOver'Which order to print the pages - one of 'downThenOver', 'overThenDown'
blackAndWhitefalsePrint without colour
draftfalsePrint with less quality (and ink)
cellComments'None'Where to place comments - one of 'atEnd', 'asDisplayed', 'None'
errors'displayed'Where to show errors - one of 'dash', 'blank', 'NA', 'displayed'
scale100Percentage value to increase or reduce the size of the print. Active when fitToPage is false
fitToWidth1How many pages wide the sheet should print on to. Active when fitToPage is true
fitToHeight1How many pages high the sheet should print on to. Active when fitToPage is true
paperSizeWhat paper size to use (see below)
showRowColHeadersfalseWhether to show the row numbers and column letters
showGridLinesfalseWhether to show grid lines
firstPageNumberWhich number to use for the first page
horizontalCenteredfalseWhether to center the sheet data horizontally
verticalCenteredfalseWhether to center the sheet data vertically

Example Paper Sizes

NameValue
Letterundefined
Legal5
Executive7
A49
A511
B5 (JIS)13
Envelope #1020
Envelope DL27
Envelope C528
Envelope B534
Envelope Monarch37
Double Japan Postcard Rotated82
16K 197x273 mm119

Headers and Footers

Here's how to add headers and footers. The added content is mainly text, such as time, introduction, file information, etc., and you can set the style of the text. In addition, you can set different texts for the first page and even page.

Note: Images are not currently supported.

// Set footer (default centered), result: "Page 2 of 16"
worksheet.headerFooter.oddFooter = "Page &P of &N";

// Set the footer (default centered) to bold, resulting in: "Page 2 of 16"
worksheet.headerFooter.oddFooter = "Page &P of &N";

// Set the left footer to 18px and italicize. Result: "Page 2 of 16"
worksheet.headerFooter.oddFooter = "&LPage &P of &N";

// Set the middle header to gray Aril, the result: "52 exceljs"
worksheet.headerFooter.oddHeader = "&C&KCCCCCC&\"Aril\"52 exceljs";

// Set the left, center, and right text of the footer. Result: “Exceljs” in the footer left. “demo.xlsx” in the footer center. “Page 2” in the footer right
worksheet.headerFooter.oddFooter = "&Lexceljs&C&F&RPage &P";

// Add different header & footer for the first page
worksheet.headerFooter.differentFirst = true;
worksheet.headerFooter.firstHeader = "Hello Exceljs";
worksheet.headerFooter.firstFooter = "Hello World"

Supported headerFooter settings

NameDefaultDescription
differentFirstfalseSet the value of differentFirst as true, which indicates that headers/footers for first page are different from the other pages
differentOddEvenfalseSet the value of differentOddEven as true, which indicates that headers/footers for odd and even pages are different
oddHeadernullSet header string for odd(default) pages, could format the string
oddFooternullSet footer string for odd(default) pages, could format the string
evenHeadernullSet header string for even pages, could format the string
evenFooternullSet footer string for even pages, could format the string
firstHeadernullSet header string for the first page, could format the string
firstFooternullSet footer string for the first page, could format the string

Script Commands

CommandsDescription
&LSet position to the left
&CSet position to the center
&RSet position to the right
&PThe current page number
&NThe total number of pages
&DThe current date
&TThe current time
&GA picture
&AThe worksheet name
&FThe file name
&BMake text bold
&IItalicize text
&UUnderline text
&"font name"font name, for example &"Aril"
&font sizefont size, for example 12
&KHEXCodefont color, for example &KCCCCCC

Worksheet Views

Worksheets now support a list of views, that control how Excel presents the sheet:

  • frozen - where a number of rows and columns to the top and left are frozen in place. Only the bottom right section will scroll
  • split - where the view is split into 4 sections, each semi-independently scrollable.

Each view also supports various properties:

NameDefaultDescription
state'normal'Controls the view state - one of normal, frozen or split
rightToLeftfalseSets the worksheet view's orientation to right-to-left
activeCellundefinedThe currently selected cell
showRulertrueShows or hides the ruler in Page Layout
showRowColHeaderstrueShows or hides the row and column headers (e.g. A1, B1 at the top and 1,2,3 on the left
showGridLinestrueShows or hides the gridlines (shown for cells where borders have not been defined)
zoomScale100Percentage zoom to use for the view
zoomScaleNormal100Normal zoom for the view
styleundefinedPresentation style - one of pageBreakPreview or pageLayout. Note pageLayout is not compatable with frozen views

Frozen Views

Frozen views support the following extra properties:

NameDefaultDescription
xSplit0How many columns to freeze. To freeze rows only, set this to 0 or undefined
ySplit0How many rows to freeze. To freeze columns only, set this to 0 or undefined
topLeftCellspecialWhich cell will be top-left in the bottom-right pane. Note: cannot be a frozen cell. Defaults to first unfrozen cell
worksheet.views = [
  {state: 'frozen', xSplit: 2, ySplit: 3, topLeftCell: 'G10', activeCell: 'A1'}
];

Split Views

Split views support the following extra properties:

NameDefaultDescription
xSplit0How many points from the left to place the splitter. To split vertically, set this to 0 or undefined
ySplit0How many points from the top to place the splitter. To split horizontally, set this to 0 or undefined
topLeftCellundefinedWhich cell will be top-left in the bottom-right pane.
activePaneundefinedWhich pane will be active - one of topLeft, topRight, bottomLeft and bottomRight
worksheet.views = [
  {state: 'split', xSplit: 2000, ySplit: 3000, topLeftCell: 'G10', activeCell: 'A1'}
];

Auto filters

It is possible to apply an auto filter to your worksheet.

worksheet.autoFilter = 'A1:C1';

While the range string is the standard form of the autoFilter, the worksheet will also support the following values:

// Set an auto filter from A1 to C1
worksheet.autoFilter = {
  from: 'A1',
  to: 'C1',
}

// Set an auto filter from the cell in row 3 and column 1
// to the cell in row 5 and column 12
worksheet.autoFilter = {
  from: {
    row: 3,
    column: 1
  },
  to: {
    row: 5,
    column: 12
  }
}

// Set an auto filter from D3 to the
// cell in row 7 and column 5
worksheet.autoFilter = {
  from: 'D3',
  to: {
    row: 7,
    column: 5
  }
}

Columns

// Add column headers and define column keys and widths
// Note: these column structures are a workbook-building convenience only,
// apart from the column width, they will not be fully persisted.
worksheet.columns = [
  { header: 'Id', key: 'id', width: 10 },
  { header: 'Name', key: 'name', width: 32 },
  { header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 }
];

// Access an individual columns by key, letter and 1-based column number
var idCol = worksheet.getColumn('id');
var nameCol = worksheet.getColumn('B');
var dobCol = worksheet.getColumn(3);

// set column properties

// Note: will overwrite cell value C1
dobCol.header = 'Date of Birth';

// Note: this will overwrite cell values C1:C2
dobCol.header = ['Date of Birth', 'A.K.A. D.O.B.'];

// from this point on, this column will be indexed by 'dob' and not 'DOB'
dobCol.key = 'dob';

dobCol.width = 15;

// Hide the column if you'd like
dobCol.hidden = true;

// set an outline level for columns
worksheet.getColumn(4).outlineLevel = 0;
worksheet.getColumn(5).outlineLevel = 1;

// columns support a readonly field to indicate the collapsed state based on outlineLevel
expect(worksheet.getColumn(4).collapsed).to.equal(false);
expect(worksheet.getColumn(5).collapsed).to.equal(true);

// iterate over all current cells in this column
dobCol.eachCell(function(cell, rowNumber) {
  // ...
});

// iterate over all current cells in this column including empty cells
dobCol.eachCell({ includeEmpty: true }, function(cell, rowNumber) {
  // ...
});

// add a column of new values
worksheet.getColumn(6).values = [1,2,3,4,5];

// add a sparse column of values
worksheet.getColumn(7).values = [,,2,3,,5,,7,,,,11];

// cut one or more columns (columns to the right are shifted left)
// If column properties have been definde, they will be cut or moved accordingly
// Known Issue: If a splice causes any merged cells to move, the results may be unpredictable
worksheet.spliceColumns(3,2);

// remove one column and insert two more.
// Note: columns 4 and above will be shifted right by 1 column.
// Also: If the worksheet has more rows than values in the colulmn inserts,
//  the rows will still be shifted as if the values existed
var newCol3Values = [1,2,3,4,5];
var newCol4Values = ['one', 'two', 'three', 'four', 'five'];
worksheet.spliceColumns(3, 1, newCol3Values, newCol4Values);

Rows

// Add a couple of Rows by key-value, after the last current row, using the column keys
worksheet.addRow({id: 1, name: 'John Doe', dob: new Date(1970,1,1)});
worksheet.addRow({id: 2, name: 'Jane Doe', dob: new Date(1965,1,7)});

// Add a row by contiguous Array (assign to columns A, B & C)
worksheet.addRow([3, 'Sam', new Date()]);

// Add a row by sparse Array (assign to columns A, E & I)
var rowValues = [];
rowValues[1] = 4;
rowValues[5] = 'Kyle';
rowValues[9] = new Date();
worksheet.addRow(rowValues);

// Add an array of rows
var rows = [
  [5,'Bob',new Date()], // row by array
  {id:6, name: 'Barbara', dob: new Date()}
];
worksheet.addRows(rows);

// Get a row object. If it doesn't already exist, a new empty one will be returned
var row = worksheet.getRow(5);

// Get the last editable row in a worksheet (or undefined if there are none)
var row = worksheet.lastRow;

// Set a specific row height
row.height = 42.5;

// make row hidden
row.hidden = true;

// set an outline level for rows
worksheet.getRow(4).outlineLevel = 0;
worksheet.getRow(5).outlineLevel = 1;

// rows support a readonly field to indicate the collapsed state based on outlineLevel
expect(worksheet.getRow(4).collapsed).to.equal(false);
expect(worksheet.getRow(5).collapsed).to.equal(true);


row.getCell(1).value = 5; // A5's value set to 5
row.getCell('name').value = 'Zeb'; // B5's value set to 'Zeb' - assuming column 2 is still keyed by name
row.getCell('C').value = new Date(); // C5's value set to now

// Get a row as a sparse array
// Note: interface change: worksheet.getRow(4) ==> worksheet.getRow(4).values
row = worksheet.getRow(4).values;
expect(row[5]).toEqual('Kyle');

// assign row values by contiguous array (where array element 0 has a value)
row.values = [1,2,3];
expect(row.getCell(1).value).toEqual(1);
expect(row.getCell(2).value).toEqual(2);
expect(row.getCell(3).value).toEqual(3);

// assign row values by sparse array  (where array element 0 is undefined)
var values = []
values[5] = 7;
values[10] = 'Hello, World!';
row.values = values;
expect(row.getCell(1).value).toBeNull();
expect(row.getCell(5).value).toEqual(7);
expect(row.getCell(10).value).toEqual('Hello, World!');

// assign row values by object, using column keys
row.values = {
  id: 13,
  name: 'Thing 1',
  dob: new Date()
};

// Insert a page break below the row
row.addPageBreak();

// Iterate over all rows that have values in a worksheet
worksheet.eachRow(function(row, rowNumber) {
  console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));
});

// Iterate over all rows (including empty rows) in a worksheet
worksheet.eachRow({ includeEmpty: true }, function(row, rowNumber) {
  console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));
});

// Iterate over all non-null cells in a row
row.eachCell(function(cell, colNumber) {
  console.log('Cell ' + colNumber + ' = ' + cell.value);
});

// Iterate over all cells in a row (including empty cells)
row.eachCell({ includeEmpty: true }, function(cell, colNumber) {
  console.log('Cell ' + colNumber + ' = ' + cell.value);
});

// Cut one or more rows (rows below are shifted up)
// Known Issue: If a splice causes any merged cells to move, the results may be unpredictable
worksheet.spliceRows(4,3);

// remove one row and insert two more.
// Note: rows 4 and below will be shifted down by 1 row.
var newRow3Values = [1,2,3,4,5];
var newRow4Values = ['one', 'two', 'three', 'four', 'five'];
worksheet.spliceRows(3, 1, newRow3Values, newRow4Values);

// Cut one or more cells (cells to the right are shifted left)
// Note: this operation will not affect other rows
row.splice(3,2);

// remove one cell and insert two more (cells to the right of the cut cell will be shifted right)
row.splice(4,1,'new value 1', 'new value 2');

// Commit a completed row to stream
row.commit();

// row metrics
var rowSize = row.cellCount;
var numValues = row.actualCellCount;

Handling Individual Cells

var cell = worksheet.getCell('C3');

// Modify/Add individual cell
cell.value = new Date(1968, 5, 1);

// query a cell's type
expect(cell.type).toEqual(Excel.ValueType.Date);

// use string value of cell
myInput.value = cell.text;

// use html-safe string for rendering...
var html = '<div>' + cell.html + '</div>';

Merged Cells

// merge a range of cells
worksheet.mergeCells('A4:B5');

// ... merged cells are linked
worksheet.getCell('B5').value = 'Hello, World!';
expect(worksheet.getCell('B5').value).toBe(worksheet.getCell('A4').value);
expect(worksheet.getCell('B5').master).toBe(worksheet.getCell('A4'));

// ... merged cells share the same style object
expect(worksheet.getCell('B5').style).toBe(worksheet.getCell('A4').style);
worksheet.getCell('B5').style.font = myFonts.arial;
expect(worksheet.getCell('A4').style.font).toBe(myFonts.arial);

// unmerging the cells breaks the style links
worksheet.unMergeCells('A4');
expect(worksheet.getCell('B5').style).not.toBe(worksheet.getCell('A4').style);
expect(worksheet.getCell('B5').style.font).not.toBe(myFonts.arial);

// merge by top-left, bottom-right
worksheet.mergeCells('K10', 'M12');

// merge by start row, start column, end row, end column (equivalent to K10:M12)
worksheet.mergeCells(10,11,12,13);

Duplicate a Row

duplicateRow(start, amount = 1, insert = true)

const wb = new ExcelJS.Workbook();
const ws = wb.addWorksheet('duplicateTest');
ws.getCell('A1').value = 'One';
ws.getCell('A2').value = 'Two';
ws.getCell('A3').value = 'Three';
ws.getCell('A4').value = 'Four';

// This line will duplicate the row 'One' twice but it will replace rows 'Two' and 'Three'
// if third param was true so it would insert 2 new rows with the values and styles of row 'One'
ws.duplicateRow(1,2,false);
ParameterDescriptionDefault Value
startRow number you want to duplicate (first in excel is 1)
amountThe times you want to duplicate the row1
inserttrue if you want to insert new rows for the duplicates, or false if you want to replace themtrue

Defined Names

Individual cells (or multiple groups of cells) can have names assigned to them. The names can be used in formulas and data validation (and probably more).

// assign (or get) a name for a cell (will overwrite any other names that cell had)
worksheet.getCell('A1').name = 'PI';
expect(worksheet.getCell('A1').name).to.equal('PI');

// assign (or get) an array of names for a cell (cells can have more than one name)
worksheet.getCell('A1').names = ['thing1', 'thing2'];
expect(worksheet.getCell('A1').names).to.have.members(['thing1', 'thing2']);

// remove a name from a cell
worksheet.getCell('A1').removeName('thing1');
expect(worksheet.getCell('A1').names).to.have.members(['thing2']);

Data Validations

Cells can define what values are valid or not and provide prompting to the user to help guide them.

Validation types can be one of the following:

TypeDescription
listDefine a discrete set of valid values. Excel will offer these in a dropdown for easy entry
wholeThe value must be a whole number
decimalThe value must be a decimal number
textLengthThe value may be text but the length is controlled
customA custom formula controls the valid values

For types other than list or custom, the following operators affect the validation:

OperatorDescription
betweenValues must lie between formula results
notBetweenValues must not lie between formula results
equalValue must equal formula result
notEqualValue must not equal formula result
greaterThanValue must be greater than formula result
lessThanValue must be less than formula result
greaterThanOrEqualValue must be greater than or equal to formula result
lessThanOrEqualValue must be less than or equal to formula result
// Specify list of valid values (One, Two, Three, Four).
// Excel will provide a dropdown with these values.
worksheet.getCell('A1').dataValidation = {
  type: 'list',
  allowBlank: true,
  formulae: ['"One,Two,Three,Four"']
};

// Specify list of valid values from a range.
// Excel will provide a dropdown with these values.
worksheet.getCell('A1').dataValidation = {
  type: 'list',
  allowBlank: true,
  formulae: ['$D$5:$F$5']
};

// Specify Cell must be a whole number that is not 5.
// Show the user an appropriate error message if they get it wrong
worksheet.getCell('A1').dataValidation = {
  type: 'whole',
  operator: 'notEqual',
  showErrorMessage: true,
  formulae: [5],
  errorStyle: 'error',
  errorTitle: 'Five',
  error: 'The value must not be Five'
};

// Specify Cell must be a decomal number between 1.5 and 7.
// Add 'tooltip' to help guid the user
worksheet.getCell('A1').dataValidation = {
  type: 'decimal',
  operator: 'between',
  allowBlank: true,
  showInputMessage: true,
  formulae: [1.5, 7],
  promptTitle: 'Decimal',
  prompt: 'The value must between 1.5 and 7'
};

// Specify Cell must be have a text length less than 15
worksheet.getCell('A1').dataValidation = {
  type: 'textLength',
  operator: 'lessThan',
  showErrorMessage: true,
  allowBlank: true,
  formulae: [15]
};

// Specify Cell must be have be a date before 1st Jan 2016
worksheet.getCell('A1').dataValidation = {
  type: 'date',
  operator: 'lessThan',
  showErrorMessage: true,
  allowBlank: true,
  formulae: [new Date(2016,0,1)]
};

Cell Comments

Add old style comment to a cell

// plain text note
worksheet.getCell('A1').note = 'Hello, ExcelJS!';

// colourful formatted note
ws.getCell('B1').note = {
  texts: [
    {'font': {'size': 12, 'color': {'theme': 0}, 'name': 'Calibri', 'family': 2, 'scheme': 'minor'}, 'text': 'This is '},
    {'font': {'italic': true, 'size': 12, 'color': {'theme': 0}, 'name': 'Calibri', 'scheme': 'minor'}, 'text': 'a'},
    {'font': {'size': 12, 'color': {'theme': 1}, 'name': 'Calibri', 'family': 2, 'scheme': 'minor'}, 'text': ' '},
    {'font': {'size': 12, 'color': {'argb': 'FFFF6600'}, 'name': 'Calibri', 'scheme': 'minor'}, 'text': 'colorful'},
    {'font': {'size': 12, 'color': {'theme': 1}, 'name': 'Calibri', 'family': 2, 'scheme': 'minor'}, 'text': ' text '},
    {'font': {'size': 12, 'color': {'argb': 'FFCCFFCC'}, 'name': 'Calibri', 'scheme': 'minor'}, 'text': 'with'},
    {'font': {'size': 12, 'color': {'theme': 1}, 'name': 'Calibri', 'family': 2, 'scheme': 'minor'}, 'text': ' in-cell '},
    {'font': {'bold': true, 'size': 12, 'color': {'theme': 1}, 'name': 'Calibri', 'family': 2, 'scheme': 'minor'}, 'text': 'format'},
  ],
};

Tables

Tables allow for in-sheet manipulation of tabular data.

To add a table to a worksheet, define a table model and call addTable:

// add a table to a sheet
ws.addTable({
  name: 'MyTable',
  ref: 'A1',
  headerRow: true,
  totalsRow: true,
  style: {
    theme: 'TableStyleDark3',
    showRowStripes: true,
  },
  columns: [
    {name: 'Date', totalsRowLabel: 'Totals:', filterButton: true},
    {name: 'Amount', totalsRowFunction: 'sum', filterButton: false},
  ],
  rows: [
    [new Date('2019-07-20'), 70.10],
    [new Date('2019-07-21'), 70.60],
    [new Date('2019-07-22'), 70.10],
  ],
});

Note: Adding a table to a worksheet will modify the sheet by placing headers and row data to the sheet. Any data on the sheet covered by the resulting table (including headers and totals) will be overwritten.

Table Properties

The following table defines the properties supported by tables.

Table PropertyDescriptionRequiredDefault Value
nameThe name of the tableY
displayNameThe display name of the tableNname
refTop left cell of the tableY
headerRowShow headers at top of tableNtrue
totalsRowShow totals at bottom of tableNfalse
styleExtra style propertiesN{}
columnsColumn definitionsY
rowsRows of dataY

Table Style Properties

The following table defines the properties supported within the table style property.

Style PropertyDescriptionRequiredDefault Value
themeThe colour theme of the tableN'TableStyleMedium2'
showFirstColumnHighlight the first column (bold)Nfalse
showLastColumnHighlight the last column (bold)Nfalse
showRowStripesAlternate rows shown with background colourNfalse
showColumnStripesAlternate rows shown with background colourNfalse

Table Column Properties

The following table defines the properties supported within each table column.

Column PropertyDescriptionRequiredDefault Value
nameThe name of the column, also used in the headerY
filterButtonSwitches the filter control in the headerNfalse
totalsRowLabelLabel to describe the totals row (first column)N'Total'
totalsRowFunctionName of the totals functionN'none'
totalsRowFormulaOptional formula for custom functionsN

Totals Functions

The following table list the valid values for the totalsRowFunction property defined by columns. If any value other than 'custom' is used, it is not necessary to include the associated formula as this will be inserted by the table.

Totals FunctionsDescription
noneNo totals function for this column
averageCompute average for the column
countNumsCount the entries that are numbers
countCount of entries
maxThe maximum value in this column
minThe minimum value in this column
stdDevThe standard deviation for this column
varThe variance for this column
sumThe sum of entries for this column
customA custom formula. Requires an associated totalsRowFormula value.

Table Style Themes

Valid theme names follow the following pattern:

Shades, Numbers can be one of:

  • Light, 1-21
  • Medium, 1-28
  • Dark, 1-11

For no theme, use the value null.

Note: custom table themes are not supported by exceljs yet.

Modifying Tables

Tables support a set of manipulation functions that allow data to be added or removed and some properties to be changed. Since many of these operations may have on-sheet effects, the changes must be committed once complete.

All index values in the table are zero based, so the first row number and first column number is 0.

Adding or Removing Headers and Totals

const table = ws.getTable('MyTable');

// turn header row on
table.headerRow = true;

// turn totals row off
table.totalsRow = false;

// commit the table changes into the sheet
table.commit();

Relocating a Table

const table = ws.getTable('MyTable');

// table top-left move to D4
table.ref = 'D4';

// commit the table changes into the sheet
table.commit();

Adding and Removing Rows

const table = ws.getTable('MyTable');

// remove first two rows
table.removeRows(0, 2);

// insert new rows at index 5
table.addRow([new Date('2019-08-05'), 5, 'Mid'], 5);

// append new row to bottom of table
table.addRow([new Date('2019-08-10'), 10, 'End']);

// commit the table changes into the sheet
table.commit();

Adding and Removing Columns

const table = ws.getTable('MyTable');

// remove second column
table.removeColumnss(1, 1);

// insert new column (with data) at index 1
table.addColumn(
  {name: 'Letter', totalsRowFunction: 'custom', totalsRowFormula: 'ROW()', totalsRowResult: 6, filterButton: true},
  ['a', 'b', 'c', 'd'],
  2
);

// commit the table changes into the sheet
table.commit();

Change Column Properties

const table = ws.getTable('MyTable');

// Get Column Wrapper for second column
const column = table.getColumn(1);

// set some properties
column.name = 'Code';
column.filterButton = true;
column.style = {font:{bold: true, name: 'Comic Sans MS'}};
column.totalsRowLabel = 'Totals';
column.totalsRowFunction = 'custom';
column.totalsRowFormula = 'ROW()';
column.totalsRowResult = 10;

// commit the table changes into the sheet
table.commit();

Styles

Cells, Rows and Columns each support a rich set of styles and formats that affect how the cells are displayed.

Styles are set by assigning the following properties:

  • numFmt
  • font
  • alignment
  • border
  • fill
// assign a style to a cell
ws.getCell('A1').numFmt = '0.00%';

// Apply styles to worksheet columns
ws.columns = [
  { header: 'Id', key: 'id', width: 10 },
  { header: 'Name', key: 'name', width: 32, style: { font: { name: 'Arial Black' } } },
  { header: 'D.O.B.', key: 'DOB', width: 10, style: { numFmt: 'dd/mm/yyyy' } }
];

// Set Column 3 to Currency Format
ws.getColumn(3).numFmt = '"£"#,##0.00;[Red]\-"£"#,##0.00';

// Set Row 2 to Comic Sans.
ws.getRow(2).font = { name: 'Comic Sans MS', family: 4, size: 16, underline: 'double', bold: true };

When a style is applied to a row or column, it will be applied to all currently existing cells in that row or column. Also, any new cell that is created will inherit its initial styles from the row and column it belongs to.

If a cell's row and column both define a specific style (e.g. font), the cell will use the row style over the column style. However if the row and column define different styles (e.g. column.numFmt and row.font), the cell will inherit the font from the row and the numFmt from the column.

Caveat: All the above properties (with the exception of numFmt, which is a string), are JS object structures. If the same style object is assigned to more than one spreadsheet entity, then each entity will share the same style object. If the style object is later modified before the spreadsheet is serialized, then all entities referencing that style object will be modified too. This behaviour is intended to prioritize performance by reducing the number of JS objects created. If you want the style objects to be independent, you will need to clone them before assigning them. Also, by default, when a document is read from file (or stream) if spreadsheet entities share similar styles, then they will reference the same style object too.

Number Formats

// display value as '1 3/5'
ws.getCell('A1').value = 1.6;
ws.getCell('A1').numFmt = '# ?/?';

// display value as '1.60%'
ws.getCell('B1').value = 0.016;
ws.getCell('B1').numFmt = '0.00%';

Fonts

// for the wannabe graphic designers out there
ws.getCell('A1').font = {
  name: 'Comic Sans MS',
  family: 4,
  size: 16,
  underline: true,
  bold: true
};

// for the graduate graphic designers...
ws.getCell('A2').font = {
  name: 'Arial Black',
  color: { argb: 'FF00FF00' },
  family: 2,
  size: 14,
  italic: true
};

// for the vertical align
ws.getCell('A3').font = {
  vertAlign: 'superscript'
};

// note: the cell will store a reference to the font object assigned.
// If the font object is changed afterwards, the cell font will change also...
var font = { name: 'Arial', size: 12 };
ws.getCell('A3').font = font;
font.size = 20; // Cell A3 now has font size 20!

// Cells that share similar fonts may reference the same font object after
// the workbook is read from file or stream
Font PropertyDescriptionExample Value(s)
nameFont name.'Arial', 'Calibri', etc.
familyFont family for fallback. An integer value.1 - Serif, 2 - Sans Serif, 3 - Mono, Others - unknown
schemeFont scheme.'minor', 'major', 'none'
charsetFont charset. An integer value.1, 2, etc.
sizeFont size. An integer value.9, 10, 12, 16, etc.
colorColour description, an object containing an ARGB value.{ argb: 'FFFF0000'}
boldFont weighttrue, false
italicFont slopetrue, false
underlineFont underline styletrue, false, 'none', 'single', 'double', 'singleAccounting', 'doubleAccounting'
strikeFont strikethroughtrue, false
outlineFont outlinetrue, false
vertAlignVertical align'superscript', 'subscript'

Alignment

// set cell alignment to top-left, middle-center, bottom-right
ws.getCell('A1').alignment = { vertical: 'top', horizontal: 'left' };
ws.getCell('B1').alignment = { vertical: 'middle', horizontal: 'center' };
ws.getCell('C1').alignment = { vertical: 'bottom', horizontal: 'right' };

// set cell to wrap-text
ws.getCell('D1').alignment = { wrapText: true };

// set cell indent to 1
ws.getCell('E1').alignment = { indent: 1 };

// set cell text rotation to 30deg upwards, 45deg downwards and vertical text
ws.getCell('F1').alignment = { textRotation: 30 };
ws.getCell('G1').alignment = { textRotation: -45 };
ws.getCell('H1').alignment = { textRotation: 'vertical' };

Valid Alignment Property Values

horizontalverticalwrapTextshrinkToFitindentreadingOrdertextRotation
lefttoptruetrueintegerrtl0 to 90
centermiddlefalsefalseltr-1 to -90
rightbottomvertical
filldistributed
justifyjustify
centerContinuous
distributed

Borders

// set single thin border around A1
ws.getCell('A1').border = {
  top: {style:'thin'},
  left: {style:'thin'},
  bottom: {style:'thin'},
  right: {style:'thin'}
};

// set double thin green border around A3
ws.getCell('A3').border = {
  top: {style:'double', color: {argb:'FF00FF00'}},
  left: {style:'double', color: {argb:'FF00FF00'}},
  bottom: {style:'double', color: {argb:'FF00FF00'}},
  right: {style:'double', color: {argb:'FF00FF00'}}
};

// set thick red cross in A5
ws.getCell('A5').border = {
  diagonal: {up: true, down: true, style:'thick', color: {argb:'FFFF0000'}}
};

Valid Border Styles

  • thin
  • dotted
  • dashDot
  • hair
  • dashDotDot
  • slantDashDot
  • mediumDashed
  • mediumDashDotDot
  • mediumDashDot
  • medium
  • double
  • thick

Fills

// fill A1 with red darkVertical stripes
ws.getCell('A1').fill = {
  type: 'pattern',
  pattern:'darkVertical',
  fgColor:{argb:'FFFF0000'}
};

// fill A2 with yellow dark trellis and blue behind
ws.getCell('A2').fill = {
  type: 'pattern',
  pattern:'darkTrellis',
  fgColor:{argb:'FFFFFF00'},
  bgColor:{argb:'FF0000FF'}
};

// fill A3 with blue-white-blue gradient from left to right
ws.getCell('A3').fill = {
  type: 'gradient',
  gradient: 'angle',
  degree: 0,
  stops: [
    {position:0, color:{argb:'FF0000FF'}},
    {position:0.5, color:{argb:'FFFFFFFF'}},
    {position:1, color:{argb:'FF0000FF'}}
  ]
};


// fill A4 with red-green gradient from center
ws.getCell('A4').fill = {
  type: 'gradient',
  gradient: 'path',
  center:{left:0.5,top:0.5},
  stops: [
    {position:0, color:{argb:'FFFF0000'}},
    {position:1, color:{argb:'FF00FF00'}}
  ]
};

Pattern Fills

PropertyRequiredDescription
typeYValue: 'pattern'Specifies this fill uses patterns
patternYSpecifies type of pattern (see Valid Pattern Types below)
fgColorNSpecifies the pattern foreground color. Default is black.
bgColorNSpecifies the pattern background color. Default is white.

Valid Pattern Types

  • none
  • solid
  • darkGray
  • mediumGray
  • lightGray
  • gray125
  • gray0625
  • darkHorizontal
  • darkVertical
  • darkDown
  • darkUp
  • darkGrid
  • darkTrellis
  • lightHorizontal
  • lightVertical
  • lightDown
  • lightUp
  • lightGrid
  • lightTrellis

Gradient Fills

PropertyRequiredDescription
typeYValue: 'gradient'Specifies this fill uses gradients
gradientYSpecifies gradient type. One of 'angle', 'path'
degreeangleFor 'angle' gradient, specifies the direction of the gradient. 0 is from the left to the right. Values from 1 - 359 rotates the direction clockwise
centerpathFor 'path' gradient. Specifies the relative coordinates for the start of the path. 'left' and 'top' values range from 0 to 1
stopsYSpecifies the gradient colour sequence. Is an array of objects containing position and color starting with position 0 and ending with position 1. Intermediary positions may be used to specify other colours on the path.

Caveats

Using the interface above it may be possible to create gradient fill effects not possible using the XLSX editor program. For example, Excel only supports angle gradients of 0, 45, 90 and 135. Similarly the sequence of stops may also be limited by the UI with positions 0,1 or 0,0.5,1 as the only options. Take care with this fill to be sure it is supported by the target XLSX viewers.

Rich Text

Individual cells now support rich text or in-cell formatting. Rich text values can control the font properties of any number of sub-strings within the text value. See Fonts for a complete list of details on what font properties are supported.

ws.getCell('A1').value = {
  'richText': [
    {'font': {'size': 12,'color': {'theme': 0},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': 'This is '},
    {'font': {'italic': true,'size': 12,'color': {'theme': 0},'name': 'Calibri','scheme': 'minor'},'text': 'a'},
    {'font': {'size': 12,'color': {'theme': 1},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': ' '},
    {'font': {'size': 12,'color': {'argb': 'FFFF6600'},'name': 'Calibri','scheme': 'minor'},'text': 'colorful'},
    {'font': {'size': 12,'color': {'theme': 1},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': ' text '},
    {'font': {'size': 12,'color': {'argb': 'FFCCFFCC'},'name': 'Calibri','scheme': 'minor'},'text': 'with'},
    {'font': {'size': 12,'color': {'theme': 1},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': ' in-cell '},
    {'font': {'bold': true,'size': 12,'color': {'theme': 1},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': 'format'}
  ]
};

expect(ws.getCell('A1').text).to.equal('This is a colorful text with in-cell format');
expect(ws.getCell('A1').type).to.equal(Excel.ValueType.RichText);

Cell Protection

Cell level protection can be modified using the protection property.

ws.getCell('A1').protection = {
  locked: false,
  hidden: true,
};

Supported Protection Properties

PropertyDefaultDescription
lockedtrueSpecifies whether a cell will be locked if the sheet is protected.
hiddenfalseSpecifies whether a cell's formula will be visible if the sheet is protected.

Conditional Formatting

Conditional formatting allows a sheet to show specific styles, icons, etc depending on cell values or any arbitrary formula.

Conditional formatting rules are added at the sheet level and will typically cover a range of cells.

Multiple rules can be applied to a given cell range and each rule will apply its own style.

If multiple rules affect a given cell, the rule priority value will determine which rule wins out if competing styles collide. The rule with the lower priority value wins. If priority values are not specified for a given rule, ExcelJS will assign them in ascending order.

Note: at present, only a subset of conditional formatting rules are supported. Specifically, only the formatting rules that do not require XML rendering inside an <extLst> element. This means that datasets and three specific icon sets (3Triangles, 3Stars, 5Boxes) are not supported.

// add a checkerboard pattern to A1:E7 based on row + col being even or odd
worksheet.addConditionalFormatting({
  ref: 'A1:E7',
  rules: [
    {
      type: 'expression',
      formulae: ['MOD(ROW()+COLUMN(),2)=0'],
      style: {fill: {type: 'pattern', pattern: 'solid', bgColor: {argb: 'FF00FF00'}}},
    }
  ]
})

Supported Conditional Formatting Rule Types

TypeDescription
expressionAny custom function may be used to activate the rule.
cellIsCompares cell value with supplied formula using specified operator
top10Applies formatting to cells with values in top (or bottom) ranges
aboveAverageApplies formatting to cells with values above (or below) average
colorScaleApplies a coloured background to cells based on where their values lie in the range
iconSetAdds one of a range of icons to cells based on value
containsTextApplies formatting based on whether cell a specific text
timePeriodApplies formatting based on whether cell datetime value lies within a specified range

Expression

FieldOptionalDefaultDescription
type'expression'
priorityY<auto>determines priority ordering of styles
formulaearray of 1 formula string that returns a true/false value. To reference the cell value, use the top-left cell address
stylestyle structure to apply if the formula returns true

Cell Is

FieldOptionalDefaultDescription
type'cellIs'
priorityY<auto>determines priority ordering of styles
operatorhow to compare cell value with formula result
formulaearray of 1 formula string that returns the value to compare against each cell
stylestyle structure to apply if the comparison returns true

Cell Is Operators

OperatorDescription
equalApply format if cell value equals formula value
greaterThanApply format if cell value is greater than formula value
lessThanApply format if cell value is less than formula value
betweenApply format if cell value is between two formula values (inclusive)

Top 10

FieldOptionalDefaultDescription
type'top10'
priorityY<auto>determines priority ordering of styles
rankY10specifies how many top (or bottom) values are included in the formatting
percentYfalseif true, the rank field is a percentage, not an absolute
bottomYfalseif true, the bottom values are included instead of the top
stylestyle structure to apply if the comparison returns true

Above Average

FieldOptionalDefaultDescription
type'aboveAverage'
priorityY<auto>determines priority ordering of styles
aboveAverageYfalseif true, the rank field is a percentage, not an absolute
stylestyle structure to apply if the comparison returns true

Colour Scale

FieldOptionalDefaultDescription
type'colorScale'
priorityY<auto>determines priority ordering of styles
cfvoarray of 2 to 5 Conditional Formatting Value Objects specifying way-points in the value range
colorcorresponding array of colours to use at given way points
stylestyle structure to apply if the comparison returns true

Icon Set

FieldOptionalDefaultDescription
type'iconSet'
priorityY<auto>determines priority ordering of styles
iconSetY3TrafficLightsname of icon set to use
cfvoarray of 2 to 5 Conditional Formatting Value Objects specifying way-points in the value range
stylestyle structure to apply if the comparison returns true

Contains Text

FieldOptionalDefaultDescription
type'containsText'
priorityY<auto>determines priority ordering of styles
operatortype of text comparison
texttext to search for
stylestyle structure to apply if the comparison returns true

Contains Text Operators

OperatorDescription
containsTextApply format if cell value contains the value specified in the 'text' field
containsBlanksApply format if cell value contains blanks
notContainsBlanksApply format if cell value does not contain blanks
containsErrorsApply format if cell value contains errors
notContainsErrorsApply format if cell value does not contain errors

Time Period

FieldOptionalDefaultDescription
type'timePeriod'
priorityY<auto>determines priority ordering of styles
timePeriodwhat time period to compare cell value to
stylestyle structure to apply if the comparison returns true

Time Periods

Time PeriodDescription
lastWeekApply format if cell value falls within the last week
thisWeekApply format if cell value falls in this week
nextWeekApply format if cell value falls in the next week
yesterdayApply format if cell value is equal to yesterday
todayApply format if cell value is equal to today
tomorrowApply format if cell value is equal to tomorrow
last7DaysApply format if cell value falls within the last 7 days
lastMonthApply format if cell value falls in last month
thisMonthApply format if cell value falls in this month
nextMonthApply format if cell value falls in next month

Outline Levels

Excel supports outlining; where rows or columns can be expanded or collapsed depending on what level of detail the user wishes to view.

Outline levels can be defined in column setup:

worksheet.columns = [
  { header: 'Id', key: 'id', width: 10 },
  { header: 'Name', key: 'name', width: 32 },
  { header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 }
];

Or directly on the row or column

worksheet.getColumn(3).outlineLevel = 1;
worksheet.getRow(3).outlineLevel = 1;

The sheet outline levels can be set on the worksheet

// set column outline level
worksheet.properties.outlineLevelCol = 1;

// set row outline level
worksheet.properties.outlineLevelRow = 1;

Note: adjusting outline levels on rows or columns or the outline levels on the worksheet will incur a side effect of also modifying the collapsed property of all rows or columns affected by the property change. E.g.:

worksheet.properties.outlineLevelCol = 1;

worksheet.getColumn(3).outlineLevel = 1;
expect(worksheet.getColumn(3).collapsed).to.be.true;

worksheet.properties.outlineLevelCol = 2;
expect(worksheet.getColumn(3).collapsed).to.be.false;

The outline properties can be set on the worksheet

worksheet.properties.outlineProperties = {
  summaryBelow: false,
  summaryRight: false,
};

Images

Adding images to a worksheet is a two-step process. First, the image is added to the workbook via the addImage() function which will also return an imageId value. Then, using the imageId, the image can be added to the worksheet either as a tiled background or covering a cell range.

Note: As of this version, adjusting or transforming the image is not supported.

Add Image to Workbook

The Workbook.addImage function supports adding images by filename or by Buffer. Note that in both cases, the extension must be specified. Valid extension values include 'jpeg', 'png', 'gif'.

// add image to workbook by filename
var imageId1 = workbook.addImage({
  filename: 'path/to/image.jpg',
  extension: 'jpeg',
});

// add image to workbook by buffer
var imageId2 = workbook.addImage({
  buffer: fs.readFileSync('path/to.image.png'),
  extension: 'png',
});

// add image to workbook by base64
var myBase64Image = "data:image/png;base64,iVBORw0KG...";
var imageId2 = workbook.addImage({
  base64: myBase64Image,
  extension: 'png',
});

Add image background to worksheet

Using the image id from Workbook.addImage, the background to a worksheet can be set using the addBackgroundImage function

// set background
worksheet.addBackgroundImage(imageId1);

Add image over a range

Using the image id from Workbook.addImage, an image can be embedded within the worksheet to cover a range. The coordinates calculated from the range will cover from the top-left of the first cell to the bottom right of the second.

// insert an image over B2:D6
worksheet.addImage(imageId2, 'B2:D6');

Using a structure instead of a range string, it is possible to partially cover cells.

Note that the coordinate system used for this is zero based, so the top-left of A1 will be { col: 0, row: 0 }. Fractions of cells can be specified by using floating point numbers, e.g. the midpoint of A1 is { col: 0.5, row: 0.5 }.

// insert an image over part of B2:D6
worksheet.addImage(imageId2, {
  tl: { col: 1.5, row: 1.5 },
  br: { col: 3.5, row: 5.5 }
});

The cell range can also have the eproperty 'editAs' which will control how the image is anchored to the cell(s) It can have one of the following values:

ValueDescription
undefinedThis is the default. It specifies the image will be moved and sized with cells
oneCellImage will be moved with cells but not sized
absoluteImage will not be moved or sized with cells
ws.addImage(imageId, {
  tl: { col: 0.1125, row: 0.4 },
  br: { col: 2.101046875, row: 3.4 },
  editAs: 'oneCell'
});

Add image to a cell

You can add an image to a cell and then define its width and height in pixels at 96dpi.

worksheet.addImage(imageId2, {
  tl: { col: 0, row: 0 },
  ext: { width: 500, height: 200 }
});

Add image with hyperlinks

You can add an image with hyperlinks to a cell, and defines the hyperlinks in image range.

worksheet.addImage(imageId2, {
  tl: { col: 0, row: 0 },
  ext: { width: 500, height: 200 },
  hyperlinks: {
    hyperlink: 'http://www.somewhere.com',
    tooltip: 'http://www.somewhere.com'
  }
});

Sheet Protection

Worksheets can be protected from modification by adding a password.

await worksheet.protect('the-password', options);

Worksheet protection can also be removed:

worksheet.unprotect();

See Cell Protection for details on how to modify individual cell protection.

Note: While the protect() function r