Gathering detailed insights and metrics for exceljs
Gathering detailed insights and metrics for exceljs
Gathering detailed insights and metrics for exceljs
Gathering detailed insights and metrics for exceljs
@types/exceljs
Stub TypeScript definitions entry for exceljs, which provides its own types definitions
exceljs-lightweight
Excel Workbook Manager - Read and Write xlsx and csv Files. Fork from exceljs/exceljs
jsreport-exceljs
Excel Workbook Manager - Read and Write xlsx and csv Files.
@zurmokeeper/exceljs
Excel Workbook Manager - Read and Write xlsx and csv Files.
npm install exceljs
Typescript
Module System
Min. Node Version
Node Version
NPM Version
81
Supply Chain
86
Quality
80
Maintenance
100
Vulnerability
94.1
License
JavaScript (99.66%)
HTML (0.23%)
TypeScript (0.1%)
Total Downloads
180,095,578
Last Day
346,588
Last Week
1,812,120
Last Month
6,221,410
Last Year
75,921,891
14,002 Stars
1,775 Commits
1,793 Forks
180 Watching
14 Branches
187 Contributors
Minified
Minified + Gzipped
Latest Version
4.4.0
Package Id
exceljs@4.4.0
Unpacked Size
20.81 MB
Size
4.50 MB
File Count
519
NPM Version
7.5.1
Node Version
15.8.0
Publised On
19 Oct 2023
Cumulative downloads
Total Downloads
Last day
-0.4%
346,588
Compared to previous day
Last week
14.6%
1,812,120
Compared to previous week
Last month
-20%
6,221,410
Compared to previous month
Last year
69.2%
75,921,891
Compared to previous year
38
Read, manipulate and write spreadsheet data and styles to XLSX and JSON.
Reverse engineered from Excel spreadsheet files as a project.
1npm install exceljs
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.
1const ExcelJS = require('exceljs');
To use the ES5 transpiled code, for example for node.js versions older than 10, use the dist/es5 path.
1const 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:
1// polyfills required by exceljs 2require('core-js/modules/es.promise'); 3require('core-js/modules/es.string.includes'); 4require('core-js/modules/es.object.assign'); 5require('core-js/modules/es.object.keys'); 6require('core-js/modules/es.symbol'); 7require('core-js/modules/es.symbol.async-iterator'); 8require('regenerator-runtime/runtime'); 9 10const ExcelJS = require('exceljs/dist/es5');
For IE 11, you'll also need a polyfill to support unicode regex patterns. For example,
1const rewritePattern = require('regexpu-core'); 2const {generateRegexpuOptions} = require('@babel/helper-create-regexp-features-plugin/lib/util'); 3 4const {RegExp} = global; 5try { 6 new RegExp('a', 'u'); 7} catch (err) { 8 global.RegExp = function(pattern, flags) { 9 if (flags && flags.includes('u')) { 10 return new RegExp(rewritePattern(pattern, flags, generateRegexpuOptions({flags, pattern}))); 11 } 12 return new RegExp(pattern, flags); 13 }; 14 global.RegExp.prototype = RegExp.prototype; 15}
ExcelJS publishes two browserified bundles inside the dist/ folder:
One with implicit dependencies on core-js polyfills...
1<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.js"></script> 2<script src="exceljs.js"></script>
And one without...
1<script src="--your-project's-pollyfills-here--"></script> 2<script src="exceljs.bare.js"></script>
1const workbook = new ExcelJS.Workbook();
1workbook.creator = 'Me'; 2workbook.lastModifiedBy = 'Her'; 3workbook.created = new Date(1985, 8, 30); 4workbook.modified = new Date(); 5workbook.lastPrinted = new Date(2016, 9, 27);
1// Set workbook dates to 1904 date system 2workbook.properties.date1904 = true;
1// Force workbook calculation on load 2workbook.calcProperties.fullCalcOnLoad = true;
The Workbook views controls how many separate windows Excel will open when viewing the workbook.
1workbook.views = [ 2 { 3 x: 0, y: 0, width: 10000, height: 20000, 4 firstSheet: 0, activeTab: 1, visibility: 'visible' 5 } 6]
1const sheet = workbook.addWorksheet('My Sheet');
Use the second parameter of the addWorksheet function to specify options for the worksheet.
For Example:
1// create a sheet with red tab colour 2const sheet = workbook.addWorksheet('My Sheet', {properties:{tabColor:{argb:'FFC0000'}}}); 3 4// create a sheet where the grid lines are hidden 5const sheet = workbook.addWorksheet('My Sheet', {views: [{showGridLines: false}]}); 6 7// create a sheet with the first row and column frozen 8const sheet = workbook.addWorksheet('My Sheet', {views:[{state: 'frozen', xSplit: 1, ySplit:1}]}); 9 10// Create worksheets with headers and footers 11const sheet = workbook.addWorksheet('My Sheet', { 12 headerFooter:{firstHeader: "Hello Exceljs", firstFooter: "Hello World"} 13}); 14 15// create new sheet with pageSetup settings for A4 - landscape 16const worksheet = workbook.addWorksheet('My Sheet', { 17 pageSetup:{paperSize: 9, orientation:'landscape'} 18});
Use the worksheet id
to remove the sheet from workbook.
For Example:
1// Create a worksheet 2const sheet = workbook.addWorksheet('My Sheet'); 3 4// Remove the worksheet using worksheet id 5workbook.removeWorksheet(sheet.id)
1// Iterate over all sheets 2// Note: workbook.worksheets.forEach will still work but this is better 3workbook.eachSheet(function(worksheet, sheetId) { 4 // ... 5}); 6 7// fetch sheet by name 8const worksheet = workbook.getWorksheet('My Sheet'); 9 10// fetch sheet by id 11// INFO: Be careful when using it! 12// It tries to access to `worksheet.id` field. Sometimes (really very often) workbook has worksheets with id not starting from 1. 13// For instance It happens when any worksheet has been deleted. 14// It's much more safety when you assume that ids are random. And stop to use this function. 15// If you need to access all worksheets in a loop please look to the next example. 16const worksheet = workbook.getWorksheet(1); 17 18// access by `worksheets` array: 19workbook.worksheets[0]; //the first one; 20
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.
1// make worksheet visible 2worksheet.state = 'visible'; 3 4// make worksheet hidden 5worksheet.state = 'hidden'; 6 7// make worksheet hidden from 'hide/unhide' dialog 8worksheet.state = 'veryHidden';
Worksheets support a property bucket to allow control over some features of the worksheet.
1// create new sheet with properties 2const worksheet = workbook.addWorksheet('sheet', {properties:{tabColor:{argb:'FF00FF00'}}}); 3 4// create a new sheet writer with properties 5const worksheetWriter = workbookWriter.addWorksheet('sheet', {properties:{outlineLevelCol:1}}); 6 7// adjust properties afterwards (not supported by worksheet-writer) 8worksheet.properties.outlineLevelCol = 2; 9worksheet.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 |
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. |
All properties that can affect the printing of a sheet are held in a pageSetup object on the sheet.
1// create new sheet with pageSetup settings for A4 - landscape 2const worksheet = workbook.addWorksheet('sheet', { 3 pageSetup:{paperSize: 9, orientation:'landscape'} 4}); 5 6// create a new sheet writer with pageSetup settings for fit-to-page 7const worksheetWriter = workbookWriter.addWorksheet('sheet', { 8 pageSetup:{fitToPage: true, fitToHeight: 5, fitToWidth: 7} 9}); 10 11// adjust pageSetup settings afterwards 12worksheet.pageSetup.margins = { 13 left: 0.7, right: 0.7, 14 top: 0.75, bottom: 0.75, 15 header: 0.3, footer: 0.3 16}; 17 18// Set Print Area for a sheet 19worksheet.pageSetup.printArea = 'A1:G20'; 20 21// Set multiple Print Areas by separating print areas with '&&' 22worksheet.pageSetup.printArea = 'A1:G10&&A11:G20'; 23 24// Repeat specific rows on every printed page 25worksheet.pageSetup.printTitlesRow = '1:3'; 26 27// Repeat specific columns on every printed page 28worksheet.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 |
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.
1 2// Create worksheets with headers and footers 3var sheet = workbook.addWorksheet('sheet', { 4 headerFooter:{firstHeader: "Hello Exceljs", firstFooter: "Hello World"} 5}); 6// Create worksheets with headers and footers 7var worksheetWriter = workbookWriter.addWorksheet('sheet', { 8 headerFooter:{firstHeader: "Hello Exceljs", firstFooter: "Hello World"} 9}); 10// Set footer (default centered), result: "Page 2 of 16" 11worksheet.headerFooter.oddFooter = "Page &P of &N"; 12 13// Set the footer (default centered) to bold, resulting in: "Page 2 of 16" 14worksheet.headerFooter.oddFooter = "Page &P of &N"; 15 16// Set the left footer to 18px and italicize. Result: "Page 2 of 16" 17worksheet.headerFooter.oddFooter = "&LPage &P of &N"; 18 19// Set the middle header to gray Aril, the result: "52 exceljs" 20worksheet.headerFooter.oddHeader = "&C&KCCCCCC&\"Aril\"52 exceljs"; 21 22// 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 23worksheet.headerFooter.oddFooter = "&Lexceljs&C&F&RPage &P"; 24 25// Add different header & footer for the first page 26worksheet.headerFooter.differentFirst = true; 27worksheet.headerFooter.firstHeader = "Hello Exceljs"; 28worksheet.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 |
Worksheets now support a list of views, that control how Excel presents the sheet:
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 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 |
1worksheet.views = [ 2 {state: 'frozen', xSplit: 2, ySplit: 3, topLeftCell: 'G10', activeCell: 'A1'} 3];
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 |
1worksheet.views = [ 2 {state: 'split', xSplit: 2000, ySplit: 3000, topLeftCell: 'G10', activeCell: 'A1'} 3];
It is possible to apply an auto filter to your worksheet.
1worksheet.autoFilter = 'A1:C1';
While the range string is the standard form of the autoFilter, the worksheet will also support the following values:
1// Set an auto filter from A1 to C1 2worksheet.autoFilter = { 3 from: 'A1', 4 to: 'C1', 5} 6 7// Set an auto filter from the cell in row 3 and column 1 8// to the cell in row 5 and column 12 9worksheet.autoFilter = { 10 from: { 11 row: 3, 12 column: 1 13 }, 14 to: { 15 row: 5, 16 column: 12 17 } 18} 19 20// Set an auto filter from D3 to the 21// cell in row 7 and column 5 22worksheet.autoFilter = { 23 from: 'D3', 24 to: { 25 row: 7, 26 column: 5 27 } 28}
1// Add column headers and define column keys and widths 2// Note: these column structures are a workbook-building convenience only, 3// apart from the column width, they will not be fully persisted. 4worksheet.columns = [ 5 { header: 'Id', key: 'id', width: 10 }, 6 { header: 'Name', key: 'name', width: 32 }, 7 { header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 } 8]; 9 10// Access an individual columns by key, letter and 1-based column number 11const idCol = worksheet.getColumn('id'); 12const nameCol = worksheet.getColumn('B'); 13const dobCol = worksheet.getColumn(3); 14 15// set column properties 16 17// Note: will overwrite cell value C1 18dobCol.header = 'Date of Birth'; 19 20// Note: this will overwrite cell values C1:C2 21dobCol.header = ['Date of Birth', 'A.K.A. D.O.B.']; 22 23// from this point on, this column will be indexed by 'dob' and not 'DOB' 24dobCol.key = 'dob'; 25 26dobCol.width = 15; 27 28// Hide the column if you'd like 29dobCol.hidden = true; 30 31// set an outline level for columns 32worksheet.getColumn(4).outlineLevel = 0; 33worksheet.getColumn(5).outlineLevel = 1; 34 35// columns support a readonly field to indicate the collapsed state based on outlineLevel 36expect(worksheet.getColumn(4).collapsed).to.equal(false); 37expect(worksheet.getColumn(5).collapsed).to.equal(true); 38 39// iterate over all current cells in this column 40dobCol.eachCell(function(cell, rowNumber) { 41 // ... 42}); 43 44// iterate over all current cells in this column including empty cells 45dobCol.eachCell({ includeEmpty: true }, function(cell, rowNumber) { 46 // ... 47}); 48 49// add a column of new values 50worksheet.getColumn(6).values = [1,2,3,4,5]; 51 52// add a sparse column of values 53worksheet.getColumn(7).values = [,,2,3,,5,,7,,,,11]; 54 55// cut one or more columns (columns to the right are shifted left) 56// If column properties have been defined, they will be cut or moved accordingly 57// Known Issue: If a splice causes any merged cells to move, the results may be unpredictable 58worksheet.spliceColumns(3,2); 59 60// remove one column and insert two more. 61// Note: columns 4 and above will be shifted right by 1 column. 62// Also: If the worksheet has more rows than values in the column inserts, 63// the rows will still be shifted as if the values existed 64const newCol3Values = [1,2,3,4,5]; 65const newCol4Values = ['one', 'two', 'three', 'four', 'five']; 66worksheet.spliceColumns(3, 1, newCol3Values, newCol4Values); 67
1// Get a row object. If it doesn't already exist, a new empty one will be returned 2const row = worksheet.getRow(5); 3 4// Get multiple row objects. If it doesn't already exist, new empty ones will be returned 5const rows = worksheet.getRows(5, 2); // start, length (>0, else undefined is returned) 6 7// Get the last editable row in a worksheet (or undefined if there are none) 8const row = worksheet.lastRow; 9 10// Set a specific row height 11row.height = 42.5; 12 13// make row hidden 14row.hidden = true; 15 16// set an outline level for rows 17worksheet.getRow(4).outlineLevel = 0; 18worksheet.getRow(5).outlineLevel = 1; 19 20// rows support a readonly field to indicate the collapsed state based on outlineLevel 21expect(worksheet.getRow(4).collapsed).to.equal(false); 22expect(worksheet.getRow(5).collapsed).to.equal(true); 23 24 25row.getCell(1).value = 5; // A5's value set to 5 26row.getCell('name').value = 'Zeb'; // B5's value set to 'Zeb' - assuming column 2 is still keyed by name 27row.getCell('C').value = new Date(); // C5's value set to now 28 29// Get a row as a sparse array 30// Note: interface change: worksheet.getRow(4) ==> worksheet.getRow(4).values 31row = worksheet.getRow(4).values; 32expect(row[5]).toEqual('Kyle'); 33 34// assign row values by contiguous array (where array element 0 has a value) 35row.values = [1,2,3]; 36expect(row.getCell(1).value).toEqual(1); 37expect(row.getCell(2).value).toEqual(2); 38expect(row.getCell(3).value).toEqual(3); 39 40// assign row values by sparse array (where array element 0 is undefined) 41const values = [] 42values[5] = 7; 43values[10] = 'Hello, World!'; 44row.values = values; 45expect(row.getCell(1).value).toBeNull(); 46expect(row.getCell(5).value).toEqual(7); 47expect(row.getCell(10).value).toEqual('Hello, World!'); 48 49// assign row values by object, using column keys 50row.values = { 51 id: 13, 52 name: 'Thing 1', 53 dob: new Date() 54}; 55 56// Insert a page break below the row 57row.addPageBreak(); 58 59// Iterate over all rows that have values in a worksheet 60worksheet.eachRow(function(row, rowNumber) { 61 console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values)); 62}); 63 64// Iterate over all rows (including empty rows) in a worksheet 65worksheet.eachRow({ includeEmpty: true }, function(row, rowNumber) { 66 console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values)); 67}); 68 69// Iterate over all non-null cells in a row 70row.eachCell(function(cell, colNumber) { 71 console.log('Cell ' + colNumber + ' = ' + cell.value); 72}); 73 74// Iterate over all cells in a row (including empty cells) 75row.eachCell({ includeEmpty: true }, function(cell, colNumber) { 76 console.log('Cell ' + colNumber + ' = ' + cell.value); 77}); 78 79// Commit a completed row to stream 80row.commit(); 81 82// row metrics 83const rowSize = row.cellCount; 84const numValues = row.actualCellCount;
1// Add a couple of Rows by key-value, after the last current row, using the column keys 2worksheet.addRow({id: 1, name: 'John Doe', dob: new Date(1970,1,1)}); 3worksheet.addRow({id: 2, name: 'Jane Doe', dob: new Date(1965,1,7)}); 4 5// Add a row by contiguous Array (assign to columns A, B & C) 6worksheet.addRow([3, 'Sam', new Date()]); 7 8// Add a row by sparse Array (assign to columns A, E & I) 9const rowValues = []; 10rowValues[1] = 4; 11rowValues[5] = 'Kyle'; 12rowValues[9] = new Date(); 13worksheet.addRow(rowValues); 14 15// Add a row with inherited style 16// This new row will have same style as last row 17// And return as row object 18const newRow = worksheet.addRow(rowValues, 'i'); 19 20// Add an array of rows 21const rows = [ 22 [5,'Bob',new Date()], // row by array 23 {id:6, name: 'Barbara', dob: new Date()} 24]; 25// add new rows and return them as array of row objects 26const newRows = worksheet.addRows(rows); 27 28// Add an array of rows with inherited style 29// These new rows will have same styles as last row 30// and return them as array of row objects 31const 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' |
1const cell = worksheet.getCell('C3'); 2 3// Modify/Add individual cell 4cell.value = new Date(1968, 5, 1); 5 6// query a cell's type 7expect(cell.type).toEqual(Excel.ValueType.Date); 8 9// use string value of cell 10myInput.value = cell.text; 11 12// use html-safe string for rendering... 13const html = '<div>' + cell.html + '</div>'; 14
1// merge a range of cells 2worksheet.mergeCells('A4:B5'); 3 4// ... merged cells are linked 5worksheet.getCell('B5').value = 'Hello, World!'; 6expect(worksheet.getCell('B5').value).toBe(worksheet.getCell('A4').value); 7expect(worksheet.getCell('B5').master).toBe(worksheet.getCell('A4')); 8 9// ... merged cells share the same style object 10expect(worksheet.getCell('B5').style).toBe(worksheet.getCell('A4').style); 11worksheet.getCell('B5').style.font = myFonts.arial; 12expect(worksheet.getCell('A4').style.font).toBe(myFonts.arial); 13 14// unmerging the cells breaks the style links 15worksheet.unMergeCells('A4'); 16expect(worksheet.getCell('B5').style).not.toBe(worksheet.getCell('A4').style); 17expect(worksheet.getCell('B5').style.font).not.toBe(myFonts.arial); 18 19// merge by top-left, bottom-right 20worksheet.mergeCells('K10', 'M12'); 21 22// merge by start row, start column, end row, end column (equivalent to K10:M12) 23worksheet.mergeCells(10,11,12,13);
1insertRow(pos, value, style = 'n') 2insertRows(pos, values, style = 'n') 3 4// Insert a couple of Rows by key-value, shifting down rows every time 5worksheet.insertRow(1, {id: 1, name: 'John Doe', dob: new Date(1970,1,1)}); 6worksheet.insertRow(1, {id: 2, name: 'Jane Doe', dob: new Date(1965,1,7)}); 7 8// Insert a row by contiguous Array (assign to columns A, B & C) 9worksheet.insertRow(1, [3, 'Sam', new Date()]); 10 11// Insert a row by sparse Array (assign to columns A, E & I) 12var rowValues = []; 13rowValues[1] = 4; 14rowValues[5] = 'Kyle'; 15rowValues[9] = new Date(); 16// insert new row and return as row object 17const insertedRow = worksheet.insertRow(1, rowValues); 18 19// Insert a row, with inherited style 20// This new row will have same style as row on top of it 21// And return as row object 22const insertedRowInherited = worksheet.insertRow(1, rowValues, 'i'); 23 24// Insert a row, keeping original style 25// This new row will have same style as it was previously 26// And return as row object 27const insertedRowOriginal = worksheet.insertRow(1, rowValues, 'o'); 28 29// Insert an array of rows, in position 1, shifting down current position 1 and later rows by 2 rows 30var rows = [ 31 [5,'Bob',new Date()], // row by array 32 {id:6, name: 'Barbara', dob: new Date()} 33]; 34// insert new rows and return them as array of row objects 35const insertedRows = worksheet.insertRows(1, rows); 36 37// Insert an array of rows, with inherited style 38// These new rows will have same style as row on top of it 39// And return them as array of row objects 40const insertedRowsInherited = worksheet.insertRows(1, rows, 'i'); 41 42// Insert an array of rows, keeping original style 43// These new rows will have same style as it was previously in 'pos' position 44const insertedRowsOriginal = worksheet.insertRows(1, rows, 'o'); 45
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' |
1// Cut one or more rows (rows below are shifted up) 2// Known Issue: If a splice causes any merged cells to move, the results may be unpredictable 3worksheet.spliceRows(4, 3); 4 5// remove one row and insert two more. 6// Note: rows 4 and below will be shifted down by 1 row. 7const newRow3Values = [1, 2, 3, 4, 5]; 8const newRow4Values = ['one', 'two', 'three', 'four', 'five']; 9worksheet.spliceRows(3, 1, newRow3Values, newRow4Values); 10 11// Cut one or more cells (cells to the right are shifted left) 12// Note: this operation will not affect other rows 13row.splice(3, 2); 14 15// remove one cell and insert two more (cells to the right of the cut cell will be shifted right) 16row.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 |
1duplicateRow(start, amount = 1, insert = true) 2 3const wb = new ExcelJS.Workbook(); 4const ws = wb.addWorksheet('duplicateTest'); 5ws.getCell('A1').value = 'One'; 6ws.getCell('A2').value = 'Two'; 7ws.getCell('A3').value = 'Three'; 8ws.getCell('A4').value = 'Four'; 9 10// This line will duplicate the row 'One' twice but it will replace rows 'Two' and 'Three' 11// if third param was true so it would insert 2 new rows with the values and styles of row 'One' 12ws.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 |
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).
1// assign (or get) a name for a cell (will overwrite any other names that cell had) 2worksheet.getCell('A1').name = 'PI'; 3expect(worksheet.getCell('A1').name).to.equal('PI'); 4 5// assign (or get) an array of names for a cell (cells can have more than one name) 6worksheet.getCell('A1').names = ['thing1', 'thing2']; 7expect(worksheet.getCell('A1').names).to.have.members(['thing1', 'thing2']); 8 9// remove a name from a cell 10worksheet.getCell('A1').removeName('thing1'); 11expect(worksheet.getCell('A1').names).to.have.members(['thing2']);
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 |
1// Specify list of valid values (One, Two, Three, Four). 2// Excel will provide a dropdown with these values. 3worksheet.getCell('A1').dataValidation = { 4 type: 'list', 5 allowBlank: true, 6 formulae: ['"One,Two,Three,Four"'] 7}; 8 9// Specify list of valid values from a range. 10// Excel will provide a dropdown with these values. 11worksheet.getCell('A1').dataValidation = { 12 type: 'list', 13 allowBlank: true, 14 formulae: ['$D$5:$F$5'] 15}; 16 17// Specify Cell must be a whole number that is not 5. 18// Show the user an appropriate error message if they get it wrong 19worksheet.getCell('A1').dataValidation = { 20 type: 'whole', 21 operator: 'notEqual', 22 showErrorMessage: true, 23 formulae: [5], 24 errorStyle: 'error', 25 errorTitle: 'Five', 26 error: 'The value must not be Five' 27}; 28 29// Specify Cell must be a decimal number between 1.5 and 7. 30// Add 'tooltip' to help guid the user 31worksheet.getCell('A1').dataValidation = { 32 type: 'decimal', 33 operator: 'between', 34 allowBlank: true, 35 showInputMessage: true, 36 formulae: [1.5, 7], 37 promptTitle: 'Decimal', 38 prompt: 'The value must between 1.5 and 7' 39}; 40 41// Specify Cell must be have a text length less than 15 42worksheet.getCell('A1').dataValidation = { 43 type: 'textLength', 44 operator: 'lessThan', 45 showErrorMessage: true, 46 allowBlank: true, 47 formulae: [15] 48}; 49 50// Specify Cell must be have be a date before 1st Jan 2016 51worksheet.getCell('A1').dataValidation = { 52 type: 'date', 53 operator: 'lessThan', 54 showErrorMessage: true, 55 allowBlank: true, 56 formulae: [new Date(2016,0,1)] 57};
Add old style comment to a cell
1// plain text note 2worksheet.getCell('A1').note = 'Hello, ExcelJS!'; 3 4// colourful formatted note 5ws.getCell('B1').note = { 6 texts: [ 7 {'font': {'size': 12, 'color': {'theme': 0}, 'name': 'Calibri', 'family': 2, 'scheme': 'minor'}, 'text': 'This is '}, 8 {'font': {'italic': true, 'size': 12, 'color': {'theme': 0}, 'name': 'Calibri', 'scheme': 'minor'}, 'text': 'a'}, 9 {'font': {'size': 12, 'color': {'theme': 1}, 'name': 'Calibri', 'family': 2, 'scheme': 'minor'}, 'text': ' '}, 10 {'font': {'size': 12, 'color': {'argb': 'FFFF6600'}, 'name': 'Calibri', 'scheme': 'minor'}, 'text': 'colorful'}, 11 {'font': {'size': 12, 'color': {'theme': 1}, 'name': 'Calibri', 'family': 2, 'scheme': 'minor'}, 'text': ' text '}, 12 {'font': {'size': 12, 'color': {'argb': 'FFCCFFCC'}, 'name': 'Calibri', 'scheme': 'minor'}, 'text': 'with'}, 13 {'font': {'size': 12, 'color': {'theme': 1}, 'name': 'Calibri', 'family': 2, 'scheme': 'minor'}, 'text': ' in-cell '}, 14 {'font': {'bold': true, 'size': 12, 'color': {'theme': 1}, 'name': 'Calibri', 'family': 2, 'scheme': 'minor'}, 'text': 'format'}, 15 ], 16 margins: { 17 insetmode: 'custom', 18 inset: [0.25, 0.25, 0.35, 0.35] 19 }, 20 protection: { 21 locked: True, 22 lockText: False 23 }, 24 editAs: 'twoCells', 25};
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 |
Determine the page margin setting mode of the cell annotation, automatic or custom mode.
1ws.getCell('B1').note.margins = { 2 insetmode: 'custom', 3 inset: [0.25, 0.25, 0.35, 0.35] 4}
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'.
Specifying the lock status of objects and object text using protection attributes.
1ws.getCell('B1').note.protection = { 2 locked: 'False', 3 lockText: 'False', 4};
Property | Required | Default Value | Description |
---|---|---|---|
locked | N | 'True' | This element specifies that the object is locked when the sheet is protected |
lockText | N | 'True' | This element specifies that the text of the object is locked |
Note: Locked objects are valid only when the worksheet is protected.
The cell comments can also have the property 'editAs' which will control how the comments is anchored to the cell(s). It can have one of the following values:
1ws.getCell('B1').note.editAs = 'twoCells';
Value | Description |
---|---|
twoCells | It specifies that the size and position of the note varies with cells |
oneCells | It specifies that the size of the note is fixed and the position changes with the cell |
absolute | This is the default. Comments will not be moved or sized with cells |
Tables allow for in-sheet manipulation of tabular data.
To add a table to a worksheet, define a table model and call addTable:
1// add a table to a sheet 2ws.addTable({ 3 name: 'MyTable', 4 ref: 'A1', 5 headerRow: true, 6 totalsRow: true, 7 style: { 8 theme: 'TableStyleDark3', 9 showRowStripes: true, 10 }, 11 columns: [ 12 {name: 'Date', totalsRowLabel: 'Totals:', filterButton: true}, 13 {name: 'Amount', totalsRowFunction: 'sum', filterButton: false}, 14 ], 15 rows: [ 16 [new Date('2019-07-20'), 70.10], 17 [new Date('2019-07-21'), 70.60], 18 [new Date('2019-07-22'), 70.10], 19 ], 20});
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.
The following table defines the properties supported by tables.
Table Property | Description | Required | Default Value |
---|---|---|---|
name | The name of the table | Y | |
displayName | The display name of the table | N | name |
ref | Top left cell of the table | Y | |
headerRow | Show headers at top of table | N | true |
totalsRow | Show totals at bottom of table | N | false |
style | Extra style properties | N | {} |
columns | Column definitions | Y | |
rows | Rows of data | Y |
The following table defines the properties supported within the table style property.
Style Property | Description | Required | Default Value |
---|---|---|---|
theme | The colour theme of the table | N | 'TableStyleMedium2' |
showFirstColumn | Highlight the first column (bold) | N | false |
showLastColumn | Highlight the last column (bold) | N | false |
showRowStripes | Alternate rows shown with background colour | N | false |
showColumnStripes | Alternate rows shown with background colour | N | false |
The following table defines the properties supported within each table column.
Column Property | Description | Required | Default Value |
---|---|---|---|
name | The name of the column, also used in the header | Y | |
filterButton | Switches the filter control in the header | N | false |
totalsRowLabel | Label to describe the totals row (first column) | N | 'Total' |
totalsRowFunction | Name of the totals function | N | 'none' |
totalsRowFormula | Optional formula for custom functions | N |
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 Functions | Description |
---|---|
none | No totals function for this column |
average | Compute average for the column |
countNums | Count the entries that are numbers |
count | Count of entries |
max | The maximum value in this column |
min | The minimum value in this column |
stdDev | The standard deviation for this column |
var | The variance for this column |
sum | The sum of entries for this column |
custom | A custom formula. Requires an associated totalsRowFormula value. |
Valid theme names follow the following pattern:
Shades, Numbers can be one of:
For no theme, use the value null.
Note: custom table themes are not supported by exceljs yet.
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
1const table = ws.getTable('MyTable'); 2 3// turn header row on 4table.headerRow = true; 5 6// turn totals row off 7table.totalsRow = false; 8 9// commit the table changes into the sheet 10table.commit();
Relocating a Table
1const table = ws.getTable('MyTable'); 2 3// table top-left move to D4 4table.ref = 'D4'; 5 6// commit the table changes into the sheet 7table.commit();
Adding and Removing Rows
1const table = ws.getTable('MyTable'); 2 3// remove first two rows 4table.removeRows(0, 2); 5 6// insert new rows at index 5 7table.addRow([new Date('2019-08-05'), 5, 'Mid'], 5); 8 9// append new row to bottom of table 10table.addRow([new Date('2019-08-10'), 10, 'End']); 11 12// commit the table changes into the sheet 13table.commit();
Adding and Removing Columns
1const table = ws.getTable('MyTable'); 2 3// remove second column 4table.removeColumns(1, 1); 5 6// insert new column (with data) at index 1 7table.addColumn( 8 {name: 'Letter', totalsRowFunction: 'custom', totalsRowFormula: 'ROW()', totalsRowResult: 6, filterButton: true}, 9 ['a', 'b', 'c', 'd'], 10 2 11); 12 13// commit the table changes into the sheet 14table.commit();
Change Column Properties
1const table = ws.getTable('MyTable'); 2 3// Get Column Wrapper for second column 4const column = table.getColumn(1); 5 6// set some properties 7column.name = 'Code'; 8column.filterButton = true; 9column.style = {font:{bold: true, name: 'Comic Sans MS'}}; 10column.totalsRowLabel = 'Totals'; 11column.totalsRowFunction = 'custom'; 12column.totalsRowFormula = 'ROW()'; 13column.totalsRowResult = 10; 14 15// commit the table changes into the sheet 16table.commit();
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:
1// assign a style to a cell 2ws.getCell('A1').numFmt = '0.00%'; 3 4// Apply styles to worksheet columns 5ws.columns = [ 6 { header: 'Id', key: 'id', width: 10 }, 7 { header: 'Name', key: 'name', width: 32, style: { font: { name: 'Arial Black' } } }, 8 { header: 'D.O.B.', key: 'DOB', width: 10, style: { numFmt: 'dd/mm/yyyy' } } 9]; 10 11// Set Column 3 to Currency Format 12ws.getColumn(3).numFmt = '"£"#,##0.00;[Red]\-"£"#,##0.00'; 13 14// Set Row 2 to Comic Sans. 15ws.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.
1// display value as '1 3/5' 2ws.getCell('A1').value = 1.6; 3ws.getCell('A1').numFmt = '# ?/?'; 4 5// display value as '1.60%' 6ws.getCell('B1').value = 0.016; 7ws.getCell('B1').numFmt = '0.00%';
1 2// for the wannabe graphic designers out there 3ws.getCell('A1').font = { 4 name: 'Comic Sans MS', 5 family: 4, 6 size: 16, 7 underline: true, 8 bold: true 9}; 10 11// for the graduate graphic designers... 12ws.getCell('A2').font = { 13 name: 'Arial Black', 14 color: { argb: 'FF00FF00' }, 15 family: 2, 16 size: 14, 17 italic: true 18}; 19 20// for the vertical align 21ws.getCell('A3').font = { 22 vertAlign: 'superscript' 23}; 24 25// note: the cell will store a reference to the font object assigned. 26// If the font object is changed afterwards, the cell font will change also... 27const font = { name: 'Arial', size: 12 }; 28ws.getCell('A3').font = font; 29font.size = 20; // Cell A3 now has font size 20! 30 31// Cells that share similar fonts may reference the same font object after 32// the workbook is read from file or stream
Font Property | Description | Example Value(s) |
---|---|---|
name | Font name. | 'Arial', 'Calibri', etc. |
family | Font family for fallback. An integer value. | 1 - Serif, 2 - Sans Serif, 3 - Mono, Others - unknown |
scheme | Font scheme. | 'minor', 'major', 'none' |
charset | Font charset. An integer value. | 1, 2, etc. |
size | Font size. An integer value. | 9, 10, 12, 16, etc. |
color | Colour description, an object containing an ARGB value. | { argb: 'FFFF0000'} |
bold | Font weight | true, false |
italic | Font slope | true, false |
underline | Font underline style | true, false, 'none', 'single', 'double', 'singleAccounting', 'doubleAccounting' |
strike | Font | true, false |
outline | Font outline | true, false |
vertAlign | Vertical align | 'superscript', 'subscript' |
1// set cell alignment to top-left, middle-center, bottom-right 2ws.getCell('A1').alignment = { vertical: 'top', horizontal: 'left' }; 3ws.getCell('B1').alignment = { vertical: 'middle', horizontal: 'center' }; 4ws.getCell('C1').alignment = { vertical: 'bottom', horizontal: 'right' }; 5 6// set cell to wrap-text 7ws.getCell('D1').alignment = { wrapText: true }; 8 9// set cell indent to 1 10ws.getCell('E1').alignment = { indent: 1 }; 11 12// set cell text rotation to 30deg upwards, 45deg downwards and vertical text 13ws.getCell('F1').alignment = { textRotation: 30 }; 14ws.getCell('G1').alignment = { textRotation: -45 }; 15ws.getCell('H1').alignment = { textRotation: 'vertical' };
Valid Alignment Property Values
horizontal | vertical | wrapText | shrinkToFit | indent | readingOrder | textRotation |
---|---|---|---|---|---|---|
left | top | true | true | integer | rtl | 0 to 90 |
center | middle | false | false | ltr | -1 to -90 | |
right | bottom | vertical | ||||
fill | distributed | |||||
justify | justify | |||||
centerContinuous | ||||||
distributed |
1// set single thin border around A1 2ws.getCell('A1').border = { 3 top: {style:'thin'}, 4 left: {style:'thin'}, 5 bottom: {style:'thin'}, 6 right: {style:'thin'} 7}; 8 9// set double thin green border around A3 10ws.getCell('A3').border = { 11 top: {style:'double', color: {argb:'FF00FF00'}}, 12 left: {style:'double', color: {argb:'FF00FF00'}}, 13 bottom: {style:'double', color: {argb:'FF00FF00'}}, 14 right: {style:'double', color: {argb:'FF00FF00'}} 15}; 16 17// set thick red cross in A5 18ws.getCell('A5').border = { 19 diagonal: {up: true, down: true, style:'thick', color: {argb:'FFFF0000'}} 20};
Valid Border Styles
1// fill A1 with red darkVertical stripes 2ws.getCell('A1').fill = { 3 type: 'pattern', 4 pattern:'darkVertical', 5 fgColor:{argb:'FFFF0000'} 6}; 7 8// fill A2 with yellow dark trellis and blue behind 9ws.getCell('A2').fill = { 10 type: 'pattern', 11 pattern:'darkTrellis', 12 fgColor