exceljs
Version:
Excel Workbook Manager - Read and Write xlsx and csv Files.
1,185 lines (943 loc) • 205 kB
Markdown
# ExcelJS
[](https://github.com/exceljs/exceljs/actions/workflows/tests.yml)
Read, manipulate and write spreadsheet data and styles to XLSX and JSON.
Reverse engineered from Excel spreadsheet files as a project.
# Translations
* [中文文档](README_zh.md)
# Installation
```shell
npm install exceljs
```
# New Features!
* Merged [fix: styles rendering in case when "numFmt" is present in conditional formatting rules (resolves #1814) #1815](https://github.com/exceljs/exceljs/pull/1815). <br/> Many thanks to [@andreykrupskii](https://github.com/andreykrupskii) for this contribution!
* Merged [inlineStr cell type support #1575 #1576](https://github.com/exceljs/exceljs/pull/1576). <br/> Many thanks to [@drdmitry](https://github.com/drdmitry) for this contribution!
* Merged [Fix parsing of boolean attributes #1849](https://github.com/exceljs/exceljs/pull/1849). <br/> Many thanks to [@bno1](https://github.com/bno1) for this contribution!
* Merged [add optional custom auto-filter to table #1670](https://github.com/exceljs/exceljs/pull/1670). <br/> Many thanks to [@thambley](https://github.com/thambley) for this contribution!
* Merged [Deep copy inherited style #1850](https://github.com/exceljs/exceljs/pull/1850). <br/> Many thanks to [@ikzhr](https://github.com/ikzhr) for this contribution!
* Merged [Upgrade actions/cache and actions/setup-node #1846](https://github.com/exceljs/exceljs/pull/1846). <br/> Many thanks to [@cclauss](https://github.com/cclauss) for this contribution!
* Merged [Check object keys in isEqual #1831](https://github.com/exceljs/exceljs/pull/1831). <br/> Many thanks to [@bno1](https://github.com/bno1) for this contribution!
* Merged [Add v17 to testing workflow #1856](https://github.com/exceljs/exceljs/pull/1856). <br/> Many thanks to [@Siemienik](https://github.com/Siemienik) for this contribution!
* Merged [Upgrade jszip to its latest version to date. This version does not have any vulnerability found by Snyk so far #1895](https://github.com/exceljs/exceljs/pull/1895). <br/> Many thanks to [@ValerioSevilla](https://github.com/ValerioSevilla) for this contribution!
* Merged [Update README.md #1677](https://github.com/exceljs/exceljs/pull/1677). <br/> Many thanks to [@xjrcode](https://github.com/xjrcode) for this contribution!
* Merged [(docs): set prototype of RegExp correctly. #1700](https://github.com/exceljs/exceljs/pull/1700). <br/> Many thanks to [@joeldenning](https://github.com/joeldenning) for this contribution!
* Merged [Added timeouts to github actions #1733](https://github.com/exceljs/exceljs/pull/1733). <br/> Many thanks to [@alexbjorlig](https://github.com/alexbjorlig) for this contribution!
* Merged [fix issue 1676 #1701](https://github.com/exceljs/exceljs/pull/1701). <br/> Many thanks to [@skypesky](https://github.com/skypesky) for this contribution!
* Merged [ExcelJS/ExcelJS#2237 : Update CI Tests, Drop support for Node v8 #2242](https://github.com/exceljs/exceljs/pull/2242). <br/> Many thanks to [@Siemienik](https://github.com/Siemienik) for this contribution!
* Merged [Fix types for getWorksheet() #2223](https://github.com/exceljs/exceljs/pull/2223). <br/> Many thanks to [@hfhchan-plb](https://github.com/hfhchan-plb) for this contribution!
* Merged [add characters cannot be used for worksheet name #2126](https://github.com/exceljs/exceljs/pull/2126). <br/> Many thanks to [@tkm-kj](https://github.com/tkm-kj) for this contribution!
* Merged [Fix issue #1753 Reject promise when workbook reader is writing to temporary file stream and error occurs #1756](https://github.com/exceljs/exceljs/pull/1756). <br/> Many thanks to [@pauliusg](https://github.com/pauliusg) for this contribution!
* Merged [README.md to have correct link for Streaming XLSX #2186](https://github.com/exceljs/exceljs/pull/2186). <br/> Many thanks to [@wulfsolter](https://github.com/wulfsolter) for this contribution!
* Merged [Added a polyfill of promise.finally to support lower versions of Firefox. #1982](https://github.com/exceljs/exceljs/pull/1982). <br/> Many thanks to [@DemoJj](https://github.com/DemoJj) for this contribution!
* Merged [Fix read this.worksheet before assign it #1934](https://github.com/exceljs/exceljs/pull/1934). <br/> Many thanks to [@ZyqGitHub1](https://github.com/ZyqGitHub1) for this contribution!
* Merged [chore: upgrade jszip to ^3.10.1 #2211](https://github.com/exceljs/exceljs/pull/2211). <br/> Many thanks to [@jarrod-cocoon](https://github.com/jarrod-cocoon) for this contribution!
* Merged [fixed spelling error in README.md file #2208](https://github.com/exceljs/exceljs/pull/2208). <br/> Many thanks to [@HugoP27](https://github.com/HugoP27) for this contribution!
* Merged [fix: Fix xlsx.writeFile() not catching error when error occurs #2244](https://github.com/exceljs/exceljs/pull/2244). <br/> Many thanks to [@zurmokeeper](https://github.com/zurmokeeper) for this contribution!
* Merged [Improve worksheets' naming validation logic. #2257](https://github.com/exceljs/exceljs/pull/2257). <br/> Many thanks to [@Siemienik](https://github.com/Siemienik) for this contribution!
* Merged [fix issue 2125 - spliceRows remove last row #2140](https://github.com/exceljs/exceljs/pull/2140). <br/> Many thanks to [@babu-ch](https://github.com/babu-ch) for this contribution!
* Merged [fix: fix the loss of column attributes due to incorrect column order #2222](https://github.com/exceljs/exceljs/pull/2222). <br/> Many thanks to [@cpaiyueyue](https://github.com/cpaiyueyue) for this contribution!
* Merged [Fix: Sheet Properties Types #2327](https://github.com/exceljs/exceljs/pull/2327). <br/> Many thanks to [@albeniraouf](https://github.com/albeniraouf) for this contribution!
* Merged [Use node 18 LTS for tsc, and benchmark. Add node 20. to test matrix. … #2354](https://github.com/exceljs/exceljs/pull/2354). <br/> Many thanks to [@Siemienik](https://github.com/Siemienik) for this contribution!
* Merged [Add missing tooltip attribute to CellHyperlinkValue index.d.ts #2350](https://github.com/exceljs/exceljs/pull/2350). <br/> Many thanks to [@NiklasPor](https://github.com/NiklasPor) for this contribution!
* Merged [Increase resilience to generating large workbooks #2320](https://github.com/exceljs/exceljs/pull/2320). <br/> Many thanks to [@hfhchan-plb](https://github.com/hfhchan-plb) for this contribution!
* Merged [repair all 'c2fo.io' links ('c2fo.github.io') #2324](https://github.com/exceljs/exceljs/pull/2324). <br/> Many thanks to [@justintunev7](https://github.com/justintunev7) for this contribution!
* Merged [fix: fix type definitions about last column, formula values and protection #2309](https://github.com/exceljs/exceljs/pull/2309). <br/> Many thanks to [@gltjk](https://github.com/gltjk) for this contribution!
* Merged [fix: add spinCount field for WorksheetProtection type #2284](https://github.com/exceljs/exceljs/pull/2284). <br/> Many thanks to [@damingerdai](https://github.com/damingerdai) for this contribution!
* Merged [Add type definition for WorksheetModel.merges #2281](https://github.com/exceljs/exceljs/pull/2281). <br/> Many thanks to [@ytjmt](https://github.com/ytjmt) for this contribution!
# 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.
### Let's chat together:
[](https://discord.gg/siema)
# Contents
<ul>
<li><a href="#importing">Importing</a></li>
<li>
<a href="#interface">Interface</a>
<ul>
<li><a href="#create-a-workbook">Create a Workbook</a></li>
<li><a href="#set-workbook-properties">Set Workbook Properties</a></li>
<li><a href="#workbook-views">Workbook Views</a></li>
<li><a href="#add-a-worksheet">Add a Worksheet</a></li>
<li><a href="#remove-a-worksheet">Remove a Worksheet</a></li>
<li><a href="#access-worksheets">Access Worksheets</a></li>
<li><a href="#worksheet-state">Worksheet State</a></li>
<li><a href="#worksheet-properties">Worksheet Properties</a></li>
<li><a href="#page-setup">Page Setup</a></li>
<li><a href="#headers-and-footers">Headers and Footers</a></li>
<li>
<a href="#worksheet-views">Worksheet Views</a>
<ul>
<li><a href="#frozen-views">Frozen Views</a></li>
<li><a href="#split-views">Split Views</a></li>
</ul>
</li>
<li><a href="#auto-filters">Auto Filters</a></li>
<li><a href="#columns">Columns</a></li>
<li><a href="#rows">Rows</a>
<ul>
<li><a href="#add-rows">Add Rows</a></li>
<li><a href="#handling-individual-cells">Handling Individual Cells</a></li>
<li><a href="#merged-cells">Merged Cells</a></li>
<li><a href="#insert-rows">Insert Rows</a></li>
<li><a href="#splice">Splice</a></li>
<li><a href="#duplicate-a-row">Duplicate Row</a></li>
</ul>
</li>
<li><a href="#defined-names">Defined Names</a></li>
<li><a href="#data-validations">Data Validations</a></li>
<li><a href="#cell-comments">Cell Comments</a></li>
<li><a href="#tables">Tables</a></li>
<li><a href="#styles">Styles</a>
<ul>
<li><a href="#number-formats">Number Formats</a></li>
<li><a href="#fonts">Fonts</a></li>
<li><a href="#alignment">Alignment</a></li>
<li><a href="#borders">Borders</a></li>
<li><a href="#fills">Fills</a></li>
<li><a href="#rich-text">Rich Text</a></li>
</ul>
</li>
<li><a href="#conditional-formatting">Conditional Formatting</a></li>
<li><a href="#outline-levels">Outline Levels</a></li>
<li><a href="#images">Images</a></li>
<li><a href="#sheet-protection">Sheet Protection</a></li>
<li><a href="#file-io">File I/O</a>
<ul>
<li><a href="#xlsx">XLSX</a>
<ul>
<li><a href="#reading-xlsx">Reading XLSX</a></li>
<li><a href="#writing-xlsx">Writing XLSX</a></li>
</ul>
</li>
<li><a href="#csv">CSV</a>
<ul>
<li><a href="#reading-csv">Reading CSV</a></li>
<li><a href="#writing-csv">Writing CSV</a></li>
</ul>
</li>
<li><a href="#streaming-io">Streaming I/O</a>
<ul>
<li><a href="#streaming-xlsx">Streaming XLSX</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#browser">Browser</a></li>
<li>
<a href="#value-types">Value Types</a>
<ul>
<li><a href="#null-value">Null Value</a></li>
<li><a href="#merge-cell">Merge Cell</a></li>
<li><a href="#number-value">Number Value</a></li>
<li><a href="#string-value">String Value</a></li>
<li><a href="#date-value">Date Value</a></li>
<li><a href="#hyperlink-value">Hyperlink Value</a></li>
<li>
<a href="#formula-value">Formula Value</a>
<ul>
<li><a href="#shared-formula">Shared Formula</a></li>
<li><a href="#formula-type">Formula Type</a></li>
<li><a href="#array-formula">Array Formula</a></li>
</ul>
</li>
<li><a href="#rich-text-value">Rich Text Value</a></li>
<li><a href="#boolean-value">Boolean Value</a></li>
<li><a href="#error-value">Error Value</a></li>
</ul>
</li>
<li><a href="#config">Config</a></li>
<li><a href="#known-issues">Known Issues</a></li>
<li><a href="#release-history">Release History</a></li>
</ul>
# Importing[⬆](#contents)<!-- Link generated with jump2header -->
```javascript
const ExcelJS = require('exceljs');
```
## ES5 Imports[⬆](#contents)<!-- Link generated with jump2header -->
To use the ES5 transpiled code, for example for node.js versions older than 10, use the dist/es5 path.
```javascript
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:
```javascript
// polyfills required by exceljs
require('core-js/modules/es.promise');
require('core-js/modules/es.string.includes');
require('core-js/modules/es.object.assign');
require('core-js/modules/es.object.keys');
require('core-js/modules/es.symbol');
require('core-js/modules/es.symbol.async-iterator');
require('regenerator-runtime/runtime');
const ExcelJS = require('exceljs/dist/es5');
```
For IE 11, you'll also need a polyfill to support unicode regex patterns. For example,
```js
const rewritePattern = require('regexpu-core');
const {generateRegexpuOptions} = require('@babel/helper-create-regexp-features-plugin/lib/util');
const {RegExp} = global;
try {
new RegExp('a', 'u');
} catch (err) {
global.RegExp = function(pattern, flags) {
if (flags && flags.includes('u')) {
return new RegExp(rewritePattern(pattern, flags, generateRegexpuOptions({flags, pattern})));
}
return new RegExp(pattern, flags);
};
global.RegExp.prototype = RegExp.prototype;
}
```
## Browserify[⬆](#contents)<!-- Link generated with jump2header -->
ExcelJS publishes two browserified bundles inside the dist/ folder:
One with implicit dependencies on core-js polyfills...
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.js"></script>
<script src="exceljs.js"></script>
```
And one without...
```html
<script src="--your-project's-pollyfills-here--"></script>
<script src="exceljs.bare.js"></script>
```
# Interface[⬆](#contents)<!-- Link generated with jump2header -->
## Create a Workbook[⬆](#contents)<!-- Link generated with jump2header -->
```javascript
const workbook = new ExcelJS.Workbook();
```
## Set Workbook Properties[⬆](#contents)<!-- Link generated with jump2header -->
```javascript
workbook.creator = 'Me';
workbook.lastModifiedBy = 'Her';
workbook.created = new Date(1985, 8, 30);
workbook.modified = new Date();
workbook.lastPrinted = new Date(2016, 9, 27);
```
```javascript
// Set workbook dates to 1904 date system
workbook.properties.date1904 = true;
```
## Set Calculation Properties[⬆](#contents)<!-- Link generated with jump2header -->
```javascript
// Force workbook calculation on load
workbook.calcProperties.fullCalcOnLoad = true;
```
## Workbook Views[⬆](#contents)<!-- Link generated with jump2header -->
The Workbook views controls how many separate windows Excel will open when viewing the workbook.
```javascript
workbook.views = [
{
x: 0, y: 0, width: 10000, height: 20000,
firstSheet: 0, activeTab: 1, visibility: 'visible'
}
]
```
## Add a Worksheet[⬆](#contents)<!-- Link generated with jump2header -->
```javascript
const sheet = workbook.addWorksheet('My Sheet');
```
Use the second parameter of the addWorksheet function to specify options for the worksheet.
For Example:
```javascript
// create a sheet with red tab colour
const sheet = workbook.addWorksheet('My Sheet', {properties:{tabColor:{argb:'FFC0000'}}});
// create a sheet where the grid lines are hidden
const sheet = workbook.addWorksheet('My Sheet', {views: [{showGridLines: false}]});
// create a sheet with the first row and column frozen
const sheet = workbook.addWorksheet('My Sheet', {views:[{state: 'frozen', xSplit: 1, ySplit:1}]});
// Create worksheets with headers and footers
const sheet = workbook.addWorksheet('My Sheet', {
headerFooter:{firstHeader: "Hello Exceljs", firstFooter: "Hello World"}
});
// create new sheet with pageSetup settings for A4 - landscape
const worksheet = workbook.addWorksheet('My Sheet', {
pageSetup:{paperSize: 9, orientation:'landscape'}
});
```
## Remove a Worksheet[⬆](#contents)<!-- Link generated with jump2header -->
Use the worksheet `id` to remove the sheet from workbook.
For Example:
```javascript
// Create a worksheet
const sheet = workbook.addWorksheet('My Sheet');
// Remove the worksheet using worksheet id
workbook.removeWorksheet(sheet.id)
```
## Access Worksheets[⬆](#contents)<!-- Link generated with jump2header -->
```javascript
// Iterate over all sheets
// Note: workbook.worksheets.forEach will still work but this is better
workbook.eachSheet(function(worksheet, sheetId) {
// ...
});
// fetch sheet by name
const worksheet = workbook.getWorksheet('My Sheet');
// fetch sheet by id
// INFO: Be careful when using it!
// It tries to access to `worksheet.id` field. Sometimes (really very often) workbook has worksheets with id not starting from 1.
// For instance It happens when any worksheet has been deleted.
// It's much more safety when you assume that ids are random. And stop to use this function.
// If you need to access all worksheets in a loop please look to the next example.
const worksheet = workbook.getWorksheet(1);
// access by `worksheets` array:
workbook.worksheets[0]; //the first one;
```
It's important to know that `workbook.getWorksheet(1) != Workbook.worksheets[0]` and `workbook.getWorksheet(1) != Workbook.worksheets[1]`,
because `workbook.worksheets[0].id` may have any value.
## Worksheet State[⬆](#contents)<!-- Link generated with jump2header -->
```javascript
// make worksheet visible
worksheet.state = 'visible';
// make worksheet hidden
worksheet.state = 'hidden';
// make worksheet hidden from 'hide/unhide' dialog
worksheet.state = 'veryHidden';
```
## Worksheet Properties[⬆](#contents)<!-- Link generated with jump2header -->
Worksheets support a property bucket to allow control over some features of the worksheet.
```javascript
// create new sheet with properties
const worksheet = workbook.addWorksheet('sheet', {properties:{tabColor:{argb:'FF00FF00'}}});
// create a new sheet writer with properties
const worksheetWriter = workbookWriter.addWorksheet('sheet', {properties:{outlineLevelCol:1}});
// adjust properties afterwards (not supported by worksheet-writer)
worksheet.properties.outlineLevelCol = 2;
worksheet.properties.defaultRowHeight = 15;
```
**Supported Properties**
| Name | Default | Description |
| ---------------- | ---------- | ----------- |
| tabColor | undefined | Color of the tabs |
| outlineLevelCol | 0 | The worksheet column outline level |
| outlineLevelRow | 0 | The worksheet row outline level |
| defaultRowHeight | 15 | Default row height |
| defaultColWidth | (optional) | Default column width |
| dyDescent | 55 | TBD |
### Worksheet Metrics[⬆](#contents)<!-- Link generated with jump2header -->
Some new metrics have been added to Worksheet...
| Name | Description |
| ----------------- | ----------- |
| rowCount | The total row size of the document. Equal to the row number of the last row that has values. |
| actualRowCount | A count of the number of rows that have values. If a mid-document row is empty, it will not be included in the count. |
| columnCount | The total column size of the document. Equal to the maximum cell count from all of the rows |
| actualColumnCount | A count of the number of columns that have values. |
## Page Setup[⬆](#contents)<!-- Link generated with jump2header -->
All properties that can affect the printing of a sheet are held in a pageSetup object on the sheet.
```javascript
// create new sheet with pageSetup settings for A4 - landscape
const worksheet = workbook.addWorksheet('sheet', {
pageSetup:{paperSize: 9, orientation:'landscape'}
});
// create a new sheet writer with pageSetup settings for fit-to-page
const worksheetWriter = workbookWriter.addWorksheet('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**
| Name | Default | Description |
| --------------------- | ------------- | ----------- |
| margins | | Whitespace on the borders of the page. Units are inches. |
| orientation | 'portrait' | Orientation of the page - i.e. taller (portrait) or wider (landscape) |
| horizontalDpi | 4294967295 | Horizontal Dots per Inch. Default value is -1 |
| verticalDpi | 4294967295 | Vertical Dots per Inch. Default value is -1 |
| fitToPage | | Whether 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'] |
| blackAndWhite | false | Print without colour |
| draft | false | Print 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'] |
| scale | 100 | Percentage value to increase or reduce the size of the print. Active when fitToPage is false |
| fitToWidth | 1 | How many pages wide the sheet should print on to. Active when fitToPage is true |
| fitToHeight | 1 | How many pages high the sheet should print on to. Active when fitToPage is true |
| paperSize | | What paper size to use (see below) |
| showRowColHeaders | false | Whether to show the row numbers and column letters |
| showGridLines | false | Whether to show grid lines |
| firstPageNumber | | Which number to use for the first page |
| horizontalCentered | false | Whether to center the sheet data horizontally |
| verticalCentered | false | Whether to center the sheet data vertically |
**Example Paper Sizes**
| Name | Value |
| ----------------------------- | --------- |
| Letter | undefined |
| Legal | 5 |
| Executive | 7 |
| A3 | 8 |
| A4 | 9 |
| A5 | 11 |
| B5 (JIS) | 13 |
| Envelope #10 | 20 |
| Envelope DL | 27 |
| Envelope C5 | 28 |
| Envelope B5 | 34 |
| Envelope Monarch | 37 |
| Double Japan Postcard Rotated | 82 |
| 16K 197x273 mm | 119 |
## Headers and Footers[⬆](#contents)<!-- Link generated with jump2header -->
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.
```javascript
// Create worksheets with headers and footers
var sheet = workbook.addWorksheet('sheet', {
headerFooter:{firstHeader: "Hello Exceljs", firstFooter: "Hello World"}
});
// Create worksheets with headers and footers
var worksheetWriter = workbookWriter.addWorksheet('sheet', {
headerFooter:{firstHeader: "Hello Exceljs", firstFooter: "Hello World"}
});
// 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**
| Name | Default | Description |
| ----------------- | --------- | ----------- |
| differentFirst | false | Set the value of differentFirst as true, which indicates that headers/footers for first page are different from the other pages |
| differentOddEven | false | Set the value of differentOddEven as true, which indicates that headers/footers for odd and even pages are different |
| oddHeader | null | Set header string for odd(default) pages, could format the string |
| oddFooter | null | Set footer string for odd(default) pages, could format the string |
| evenHeader | null | Set header string for even pages, could format the string |
| evenFooter | null | Set footer string for even pages, could format the string |
| firstHeader | null | Set header string for the first page, could format the string |
| firstFooter | null | Set footer string for the first page, could format the string |
**Script Commands**
| Commands | Description |
| ------------ | ----------- |
| &L | Set position to the left |
| &C | Set position to the center |
| &R | Set position to the right |
| &P | The current page number |
| &N | The total number of pages |
| &D | The current date |
| &T | The current time |
| &G | A picture |
| &A | The worksheet name |
| &F | The file name |
| &B | Make text bold |
| &I | Italicize text |
| &U | Underline text |
| &"font name" | font name, for example &"Aril" |
| &font size | font size, for example 12 |
| &KHEXCode | font color, for example &KCCCCCC |
## Worksheet Views[⬆](#contents)<!-- Link generated with jump2header -->
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:
| Name | Default | Description |
| ----------------- | --------- | ----------- |
| state | 'normal' | Controls the view state - one of normal, frozen or split |
| rightToLeft | false | Sets the worksheet view's orientation to right-to-left |
| activeCell | undefined | The currently selected cell |
| showRuler | true | Shows or hides the ruler in Page Layout |
| showRowColHeaders | true | Shows or hides the row and column headers (e.g. A1, B1 at the top and 1,2,3 on the left |
| showGridLines | true | Shows or hides the gridlines (shown for cells where borders have not been defined) |
| zoomScale | 100 | Percentage zoom to use for the view |
| zoomScaleNormal | 100 | Normal zoom for the view |
| style | undefined | Presentation style - one of pageBreakPreview or pageLayout. Note pageLayout is not compatible with frozen views |
### Frozen Views[⬆](#contents)<!-- Link generated with jump2header -->
Frozen views support the following extra properties:
| Name | Default | Description |
| ----------------- | --------- | ----------- |
| xSplit | 0 | How many columns to freeze. To freeze rows only, set this to 0 or undefined |
| ySplit | 0 | How many rows to freeze. To freeze columns only, set this to 0 or undefined |
| topLeftCell | special | Which cell will be top-left in the bottom-right pane. Note: cannot be a frozen cell. Defaults to first unfrozen cell |
```javascript
worksheet.views = [
{state: 'frozen', xSplit: 2, ySplit: 3, topLeftCell: 'G10', activeCell: 'A1'}
];
```
### Split Views[⬆](#contents)<!-- Link generated with jump2header -->
Split views support the following extra properties:
| Name | Default | Description |
| ----------------- | --------- | ----------- |
| xSplit | 0 | How many points from the left to place the splitter. To split vertically, set this to 0 or undefined |
| ySplit | 0 | How many points from the top to place the splitter. To split horizontally, set this to 0 or undefined |
| topLeftCell | undefined | Which cell will be top-left in the bottom-right pane. |
| activePane | undefined | Which pane will be active - one of topLeft, topRight, bottomLeft and bottomRight |
```javascript
worksheet.views = [
{state: 'split', xSplit: 2000, ySplit: 3000, topLeftCell: 'G10', activeCell: 'A1'}
];
```
## Auto filters[⬆](#contents)<!-- Link generated with jump2header -->
It is possible to apply an auto filter to your worksheet.
```javascript
worksheet.autoFilter = 'A1:C1';
```
While the range string is the standard form of the autoFilter, the worksheet will also support the
following values:
```javascript
// 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[⬆](#contents)<!-- Link generated with jump2header -->
```javascript
// 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
const idCol = worksheet.getColumn('id');
const nameCol = worksheet.getColumn('B');
const 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 defined, 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 column inserts,
// the rows will still be shifted as if the values existed
const newCol3Values = [1,2,3,4,5];
const newCol4Values = ['one', 'two', 'three', 'four', 'five'];
worksheet.spliceColumns(3, 1, newCol3Values, newCol4Values);
```
## Rows[⬆](#contents)<!-- Link generated with jump2header -->
```javascript
// Get a row object. If it doesn't already exist, a new empty one will be returned
const row = worksheet.getRow(5);
// Get multiple row objects. If it doesn't already exist, new empty ones will be returned
const rows = worksheet.getRows(5, 2); // start, length (>0, else undefined is returned)
// Get the last editable row in a worksheet (or undefined if there are none)
const 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)
const 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);
});
// Commit a completed row to stream
row.commit();
// row metrics
const rowSize = row.cellCount;
const numValues = row.actualCellCount;
```
## Add Rows[⬆](#contents)<!-- Link generated with jump2header -->
```javascript
// 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)
const rowValues = [];
rowValues[1] = 4;
rowValues[5] = 'Kyle';
rowValues[9] = new Date();
worksheet.addRow(rowValues);
// Add a row with inherited style
// This new row will have same style as last row
// And return as row object
const newRow = worksheet.addRow(rowValues, 'i');
// Add an array of rows
const rows = [
[5,'Bob',new Date()], // row by array
{id:6, name: 'Barbara', dob: new Date()}
];
// add new rows and return them as array of row objects
const newRows = worksheet.addRows(rows);
// Add an array of rows with inherited style
// These new rows will have same styles as last row
// and return them as array of row objects
const newRowsStyled = worksheet.addRows(rows, 'i');
```
| Parameter | Description | Default Value |
| -------------- | ----------------- | -------- |
| value/s | The new row/s values | |
| style | 'i' for inherit from row above, 'i+' to include empty cells, 'n' for none | *'n'* |
## Handling Individual Cells[⬆](#contents)<!-- Link generated with jump2header -->
```javascript
const 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...
const html = '<div>' + cell.html + '</div>';
```
## Merged Cells[⬆](#contents)<!-- Link generated with jump2header -->
```javascript
// 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);
```
## Insert Rows[⬆](#contents)<!-- Link generated with jump2header -->
```javascript
insertRow(pos, value, style = 'n')
insertRows(pos, values, style = 'n')
// Insert a couple of Rows by key-value, shifting down rows every time
worksheet.insertRow(1, {id: 1, name: 'John Doe', dob: new Date(1970,1,1)});
worksheet.insertRow(1, {id: 2, name: 'Jane Doe', dob: new Date(1965,1,7)});
// Insert a row by contiguous Array (assign to columns A, B & C)
worksheet.insertRow(1, [3, 'Sam', new Date()]);
// Insert a row by sparse Array (assign to columns A, E & I)
var rowValues = [];
rowValues[1] = 4;
rowValues[5] = 'Kyle';
rowValues[9] = new Date();
// insert new row and return as row object
const insertedRow = worksheet.insertRow(1, rowValues);
// Insert a row, with inherited style
// This new row will have same style as row on top of it
// And return as row object
const insertedRowInherited = worksheet.insertRow(1, rowValues, 'i');
// Insert a row, keeping original style
// This new row will have same style as it was previously
// And return as row object
const insertedRowOriginal = worksheet.insertRow(1, rowValues, 'o');
// Insert an array of rows, in position 1, shifting down current position 1 and later rows by 2 rows
var rows = [
[5,'Bob',new Date()], // row by array
{id:6, name: 'Barbara', dob: new Date()}
];
// insert new rows and return them as array of row objects
const insertedRows = worksheet.insertRows(1, rows);
// Insert an array of rows, with inherited style
// These new rows will have same style as row on top of it
// And return them as array of row objects
const insertedRowsInherited = worksheet.insertRows(1, rows, 'i');
// Insert an array of rows, keeping original style
// These new rows will have same style as it was previously in 'pos' position
const insertedRowsOriginal = worksheet.insertRows(1, rows, 'o');
```
| Parameter | Description | Default Value |
| -------------- | ----------------- | -------- |
| pos | Row number where you want to insert, pushing down all rows from there | |
| value/s | The new row/s values | |
| style | 'i' for inherit from row above, , 'i+' to include empty cells, 'o' for original style, 'o+' to include empty cells, 'n' for none | *'n'* |
## Splice[⬆](#contents)<!-- Link generated with jump2header -->
```javascript
// 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.
const newRow3Values = [1, 2, 3, 4, 5];
const 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');
```
| Parameter | Description | Default Value |
| -------------- | ----------------- | -------- |
| start | Starting point to splice from | |
| count | Number of rows/cells to remove | |
| ...inserts | New row/cell values to insert | |
## Duplicate a Row[⬆](#contents)<!-- Link generated with jump2header -->
```javascript
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);
```
| Parameter | Description | Default Value |
| -------------- | ----------------- | -------- |
| start | Row number you want to duplicate (first in excel is 1) | |
| amount | The times you want to duplicate the row | 1 |
| insert | *true* if you want to insert new rows for the duplicates, or *false* if you want to replace them | *true* |
## Defined Names[⬆](#contents)<!-- Link generated with jump2header -->
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).
```javascript
// 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[⬆](#contents)<!-- Link generated with jump2header -->
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:
| Type | Description |
| ---------- | ----------- |
| list | Define a discrete set of valid values. Excel will offer these in a dropdown for easy entry |
| whole | The value must be a whole number |
| decimal | The value must be a decimal number |
| textLength | The value may be text but the length is controlled |
| custom | A custom formula controls the valid values |
For types other than list or custom, the following operators affect the validation:
| Operator | Description |
| -------------------- | ----------- |
| between | Values must lie between formula results |
| notBetween | Values must not lie between formula results |
| equal | Value must equal formula result |
| notEqual | Value must not equal formula result |
| greaterThan | Value must be greater than formula result |
| lessThan | Value must be less than formula result |
| greaterThanOrEqual | Value must be greater than or equal to formula result |
| lessThanOrEqual | Value must be less than or equal to formula result |
```javascript
// 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 decimal 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[⬆](#contents)<!-- Link generated with jump2header -->
Add old style comment to a cell
```javascript
// 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'},
],
margins: {
insetmode: 'custom',
inset: [0.25, 0.25, 0.35, 0.35]
},
protection: {
locked: True,
lockText: False
},
editAs: 'twoCells',
};
```
### Cell Comments Properties[⬆](#contents)<!-- Link generated with jump2header -->
The following table defines the properties supported by cell comments.
| Field | Required | Default Value | Description |
| -------- | -------- | ------------- | ----------- |
| texts | Y | | The text of the comment |
| margins | N | {} | Determines the value of margins for automatic or custom cell comments
| protection | N | {} | Specifying the lock status of objects and object text using protection attributes |
| editAs | N | 'absolute' | Use the 'editAs' attribute to specify how the annotation is anchored to the cell |
### Cell Comments Margins
Determine the page margin setting mode of the cell annotation, automatic or custom mode.
```javascript
ws.getCell('B1').note.margins = {
insetmode: 'custom',
inset: [0.25, 0.25, 0.35, 0.35]
}
```
### Supported Margins Properties[⬆](#contents)<!-- Link generated with jump2header -->
| Property | Required | Default Value | Description |
| -------- | -------- | ------------- | ----------- |
| insetmode | N | 'auto' | Determines whether comment margins are set automatically and the value is 'auto' or 'custom' |
| inset | N | [0.13, 0.13, 0.25, 0.25] | Whitespace on the borders of the comment. Units are centimeter. Direction is left, top, right, bottom |
Note: This ```inset``` setting takes effect only when the value of ```insetmode``` is 'custom'.
### Cell Comments Protection
Specifying the lock status of obje