Installations
npm install exceljs-lightweight
Developer Guide
Typescript
Yes
Module System
CommonJS, UMD
Min. Node Version
>=6.0.0
Node Version
10.15.2
NPM Version
6.11.2
Score
61.9
Supply Chain
84.8
Quality
69.6
Maintenance
50
Vulnerability
95.2
License
Releases
Unable to fetch releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (99.71%)
HTML (0.29%)
Developer
havietduc91
Download Statistics
Total Downloads
88,892
Last Day
4
Last Week
83
Last Month
799
Last Year
4,544
GitHub Statistics
1 Stars
981 Commits
1 Forks
1 Watching
8 Branches
1 Contributors
Bundle Size
372.25 kB
Minified
98.88 kB
Minified + Gzipped
Package Meta Information
Latest Version
1.14.0
Package Id
exceljs-lightweight@1.14.0
Unpacked Size
3.51 MB
Size
792.38 kB
File Count
375
NPM Version
6.11.2
Node Version
10.15.2
Total Downloads
Cumulative downloads
Total Downloads
88,892
Last day
-92.9%
4
Compared to previous day
Last week
-81.7%
83
Compared to previous week
Last month
418.8%
799
Compared to previous month
Last year
-75.3%
4,544
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dev Dependencies
36
Exceljs-lightweight
First of all, this repository was forked from exceljs/exceljs
with branch 1.12.0
and then replace moment
with dayjs
to make exceljs more lightweight.
The reason that we don't use exceljs with version is 3.3.0
because of the size is big, it tooks around 900KB.
So we have to create exceljs-lightweight
.
Read, manipulate and write spreadsheet data and styles to XLSX and JSON.
Reverse engineered from Excel spreadsheet files as a project.
Installation
1npm install exceljs-lightweight
New Features!
- Merged Feat configure headers and footers #863. Many thanks to autukill 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.
To be clear, all contributions added to this library will be included in the library's MIT licence.
Backlog
- ESLint - slowly turn on (justifyable) rules which should, I hope, help make contributions easier.
- Conditional Formatting.
- There are still more print-settings to add; Fixed rows/cols, etc.
- XLSX Streaming Reader.
- Parsing CSV with Headers
Contents
-
Interface
- Create a Workbook
- Set Workbook Properties
- Workbook Views
- Add a Worksheet
- Remove a Worksheet
- Access Worksheets
- Worksheet State
- Worksheet Properties
- Page Setup
- Headers and Footers
- Worksheet Views
- Auto Filters
- Columns
- Rows
- Handling Individual Cells
- Merged Cells
- Defined Names
- Data Validations
- Styles
- Outline Levels
- Images
- File I/O
- Browser
- Value Types
- Config
- Known Issues
- Release History
Interface
Importing
The default export is a transpiled ES5 version with a Promise polyfill - this offers the highest level of compatibility.
1var Excel = require('exceljs-lightweight'); 2import Excel from 'exceljs-lightweight';
However, if you use this library on a modern node.js version (>=8) or on the frontend using a bundler (or can focus on just evergreen browsers), we recommend to use these imports:
1const Excel = require('exceljs-lightweight/modern.nodejs'); 2import Excel from 'exceljs-lightweight/modern.browser';
Create a Workbook
1var workbook = new Excel.Workbook();
Set Workbook Properties
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;
Workbook Views
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]
Add a Worksheet
1var 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 2var sheet = workbook.addWorksheet('My Sheet', {properties:{tabColor:{argb:'FFC0000'}}}); 3 4// create a sheet where the grid lines are hidden 5var sheet = workbook.addWorksheet('My Sheet', {properties: {showGridLines: false}}); 6 7// create a sheet with the first row and column frozen 8var sheet = workbook.addWorksheet('My Sheet', {views:[{xSplit: 1, ySplit:1}]});
Remove a Worksheet
Use the worksheet id
to remove the sheet from workbook.
For Example:
1// Create a worksheet 2var sheet = workbook.addWorksheet('My Sheet'); 3 4// Remove the worksheet using worksheet id 5workbook.removeWorksheet(sheet.id)
Access Worksheets
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 8var worksheet = workbook.getWorksheet('My Sheet'); 9 10// fetch sheet by id 11var worksheet = workbook.getWorksheet(1);
Worksheet State
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';
Worksheet Properties
Worksheets support a property bucket to allow control over some features of the worksheet.
1// create new sheet with properties 2var worksheet = workbook.addWorksheet('sheet', {properties:{tabColor:{argb:'FF00FF00'}}}); 3 4// create a new sheet writer with properties 5var worksheetWriter = workbookWriter.addSheet('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 |
dyDescent | 55 | TBD |
Worksheet Metrics
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
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 2var 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 7var worksheetWriter = workbookWriter.addSheet('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// Repeat specific rows on every printed page 22worksheet.pageSetup.printTitlesRow = '1:3'; 23 24// Repeat specific columns on every printed page 25worksheet.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 |
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
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// Set footer (default centered), result: "Page 2 of 16" 2worksheet.headerFooter.oddFooter = "Page &P of &N"; 3 4// Set the footer (default centered) to bold, resulting in: "Page 2 of 16" 5worksheet.headerFooter.oddFooter = "Page &P of &N"; 6 7// Set the left footer to 18px and italicize. Result: "Page 2 of 16" 8worksheet.headerFooter.oddFooter = "&LPage &P of &N"; 9 10// Set the middle header to gray Aril, the result: "52 exceljs" 11worksheet.headerFooter.oddHeader = "&C&KCCCCCC&\"Aril\"52 exceljs"; 12 13// 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 14worksheet.headerFooter.oddFooter = "&Lexceljs&C&F&RPage &P"; 15 16// Add different header & footer for the first page 17worksheet.headerFooter.differentFirst = true; 18worksheet.headerFooter.firstHeader = "Hello Exceljs"; 19worksheet.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
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 left 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 compatable with frozen views |
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
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];
Auto filters
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}
Columns
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 11var idCol = worksheet.getColumn('id'); 12var nameCol = worksheet.getColumn('B'); 13var 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 definde, 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 colulmn inserts, 63// the rows will still be shifted as if the values existed 64var newCol3Values = [1,2,3,4,5]; 65var newCol4Values = ['one', 'two', 'three', 'four', 'five']; 66worksheet.spliceColumns(3, 1, newCol3Values, newCol4Values); 67
Rows
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) 9var rowValues = []; 10rowValues[1] = 4; 11rowValues[5] = 'Kyle'; 12rowValues[9] = new Date(); 13worksheet.addRow(rowValues); 14 15// Add an array of rows 16var rows = [ 17 [5,'Bob',new Date()], // row by array 18 {id:6, name: 'Barbara', dob: new Date()} 19]; 20worksheet.addRows(rows); 21 22// Get a row object. If it doesn't already exist, a new empty one will be returned 23var row = worksheet.getRow(5); 24 25// Get the last editable row in a worksheet (or undefined if there are none) 26var row = worksheet.lastRow; 27 28// Set a specific row height 29row.height = 42.5; 30 31// make row hidden 32row.hidden = true; 33 34// set an outline level for rows 35worksheet.getRow(4).outlineLevel = 0; 36worksheet.getRow(5).outlineLevel = 1; 37 38// rows support a readonly field to indicate the collapsed state based on outlineLevel 39expect(worksheet.getRow(4).collapsed).to.equal(false); 40expect(worksheet.getRow(5).collapsed).to.equal(true); 41 42 43row.getCell(1).value = 5; // A5's value set to 5 44row.getCell('name').value = 'Zeb'; // B5's value set to 'Zeb' - assuming column 2 is still keyed by name 45row.getCell('C').value = new Date(); // C5's value set to now 46 47// Get a row as a sparse array 48// Note: interface change: worksheet.getRow(4) ==> worksheet.getRow(4).values 49row = worksheet.getRow(4).values; 50expect(row[5]).toEqual('Kyle'); 51 52// assign row values by contiguous array (where array element 0 has a value) 53row.values = [1,2,3]; 54expect(row.getCell(1).value).toEqual(1); 55expect(row.getCell(2).value).toEqual(2); 56expect(row.getCell(3).value).toEqual(3); 57 58// assign row values by sparse array (where array element 0 is undefined) 59var values = [] 60values[5] = 7; 61values[10] = 'Hello, World!'; 62row.values = values; 63expect(row.getCell(1).value).toBeNull(); 64expect(row.getCell(5).value).toEqual(7); 65expect(row.getCell(10).value).toEqual('Hello, World!'); 66 67// assign row values by object, using column keys 68row.values = { 69 id: 13, 70 name: 'Thing 1', 71 dob: new Date() 72}; 73 74// Insert a page break below the row 75row.addPageBreak(); 76 77// Iterate over all rows that have values in a worksheet 78worksheet.eachRow(function(row, rowNumber) { 79 console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values)); 80}); 81 82// Iterate over all rows (including empty rows) in a worksheet 83worksheet.eachRow({ includeEmpty: true }, function(row, rowNumber) { 84 console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values)); 85}); 86 87// Iterate over all non-null cells in a row 88row.eachCell(function(cell, colNumber) { 89 console.log('Cell ' + colNumber + ' = ' + cell.value); 90}); 91 92// Iterate over all cells in a row (including empty cells) 93row.eachCell({ includeEmpty: true }, function(cell, colNumber) { 94 console.log('Cell ' + colNumber + ' = ' + cell.value); 95}); 96 97// Cut one or more rows (rows below are shifted up) 98// Known Issue: If a splice causes any merged cells to move, the results may be unpredictable 99worksheet.spliceRows(4,3); 100 101// remove one row and insert two more. 102// Note: rows 4 and below will be shifted down by 1 row. 103var newRow3Values = [1,2,3,4,5]; 104var newRow4Values = ['one', 'two', 'three', 'four', 'five']; 105worksheet.spliceRows(3, 1, newRow3Values, newRow4Values); 106 107// Cut one or more cells (cells to the right are shifted left) 108// Note: this operation will not affect other rows 109row.splice(3,2); 110 111// remove one cell and insert two more (cells to the right of the cut cell will be shifted right) 112row.splice(4,1,'new value 1', 'new value 2'); 113 114// Commit a completed row to stream 115row.commit(); 116 117// row metrics 118var rowSize = row.cellCount; 119var numValues = row.actualCellCount;
Handling Individual Cells
1var 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... 13var html = '<div>' + cell.html + '</div>'; 14
Merged Cells
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('G10', 'H11'); 21worksheet.mergeCells(10,11,12,13); // top,left,bottom,right
Defined Names
Individual cells (or multiple groups of cells) can have names assigned to them. The names can be used in formulas and data validation (and probably more).
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']);
Data Validations
Cells can define what values are valid or not and provide prompting to the user to help guide them.
Validation types can be one of the following:
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 decomal 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};
Cell Comments
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};
Styles
Cells, Rows and Columns each support a rich set of styles and formats that affect how the cells are displayed.
Styles are set by assigning the following properties:
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.
Number Formats
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%';
Fonts
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... 27var 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' |
Alignment
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 | indent | readingOrder | textRotation |
---|---|---|---|---|---|
left | top | true | integer | rtl | 0 to 90 |
center | middle | false | ltr | -1 to -90 | |
right | bottom | vertical | |||
fill | distributed | ||||
justify | justify | ||||
centerContinuous | |||||
distributed |
Borders
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
- thin
- dotted
- dashDot
- hair
- dashDotDot
- slantDashDot
- mediumDashed
- mediumDashDotDot
- mediumDashDot
- medium
- double
- thick
Fills
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:{argb:'FFFFFF00'}, 13 bgColor:{argb:'FF0000FF'} 14}; 15 16// fill A3 with blue-white-blue gradient from left to right 17ws.getCell('A3').fill = { 18 type: 'gradient', 19 gradient: 'angle', 20 degree: 0, 21 stops: [ 22 {position:0, color:{argb:'FF0000FF'}}, 23 {position:0.5, color:{argb:'FFFFFFFF'}}, 24 {position:1, color:{argb:'FF0000FF'}} 25 ] 26}; 27 28 29// fill A4 with red-green gradient from center 30ws.getCell('A2').fill = { 31 type: 'gradient', 32 gradient: 'path', 33 center:{left:0.5,top:0.5}, 34 stops: [ 35 {position:0, color:{argb:'FFFF0000'}}, 36 {position:1, color:{argb:'FF00FF00'}} 37 ] 38};
Pattern Fills
Property | Required | Description |
---|---|---|
type | Y | Value: 'pattern' Specifies this fill uses patterns |
pattern | Y | Specifies type of pattern (see Valid Pattern Types below) |
fgColor | N | Specifies the pattern foreground color. Default is black. |
bgColor | N | Specifies the pattern background color. Default is white. |
Valid Pattern Types
- none
- solid
- darkGray
- mediumGray
- lightGray
- gray125
- gray0625
- darkHorizontal
- darkVertical
- darkDown
- darkUp
- darkGrid
- darkTrellis
- lightHorizontal
- lightVertical
- lightDown
- lightUp
- lightGrid
- lightTrellis
Gradient Fills
Property | Required | Description |
---|---|---|
type | Y | Value: 'gradient' Specifies this fill uses gradients |
gradient | Y | Specifies gradient type. One of ['angle', 'path'] |
degree | angle | For 'angle' gradient, specifies the direction of the gradient. 0 is from the left to the right. Values from 1 - 359 rotates the direction clockwise |
center | path | For 'path' gradient. Specifies the relative coordinates for the start of the path. 'left' and 'top' values range from 0 to 1 |
stops | Y | Specifies the gradient colour sequence. Is an array of objects containing position and color starting with position 0 and ending with position 1. Intermediary positions may be used to specify other colours on the path. |
Caveats
Using the interface above it may be possible to create gradient fill effects not possible using the XLSX editor program. For example, Excel only supports angle gradients of 0, 45, 90 and 135. Similarly the sequence of stops may also be limited by the UI with positions [0,1] or [0,0.5,1] as the only options. Take care with this fill to be sure it is supported by the target XLSX viewers.
Rich Text
Individual cells now support rich text or in-cell formatting. Rich text values can control the font properties of any number of sub-strings within the text value. See Fonts for a complete list of details on what font properties are supported.
1 2ws.getCell('A1').value = { 3 'richText': [ 4 {'font': {'size': 12,'color': {'theme': 0},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': 'This is '}, 5 {'font': {'italic': true,'size': 12,'color': {'theme': 0},'name': 'Calibri','scheme': 'minor'},'text': 'a'}, 6 {'font': {'size': 12,'color': {'theme': 1},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': ' '}, 7 {'font': {'size': 12,'color': {'argb': 'FFFF6600'},'name': 'Calibri','scheme': 'minor'},'text': 'colorful'}, 8 {'font': {'size': 12,'color': {'theme': 1},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': ' text '}, 9 {'font': {'size': 12,'color': {'argb': 'FFCCFFCC'},'name': 'Calibri','scheme': 'minor'},'text': 'with'}, 10 {'font': {'size': 12,'color': {'theme': 1},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': ' in-cell '}, 11 {'font': {'bold': true,'size': 12,'color': {'theme': 1},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': 'format'} 12 ] 13}; 14 15expect(ws.getCell('A1').text).to.equal('This is a colorful text with in-cell format'); 16expect(ws.getCell('A1').type).to.equal(Excel.ValueType.RichText); 17
Outline Levels
Excel supports outlining; where rows or columns can be expanded or collapsed depending on what level of detail the user wishes to view.
Outline levels can be defined in column setup:
1worksheet.columns = [ 2 { header: 'Id', key: 'id', width: 10 }, 3 { header: 'Name', key: 'name', width: 32 }, 4 { header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 } 5];
Or directly on the row or column
1worksheet.getColumn(3).outlineLevel = 1; 2worksheet.getRow(3).outlineLevel = 1;
The sheet outline levels can be set on the worksheet
1// set column outline level 2worksheet.properties.outlineLevelCol = 1; 3 4// set row outline level 5worksheet.properties.outlineLevelRow = 1;
Note: adjusting outline levels on rows or columns or the outline levels on the worksheet will incur a side effect of also modifying the collapsed property of all rows or columns affected by the property change. E.g.:
1worksheet.properties.outlineLevelCol = 1; 2 3worksheet.getColumn(3).outlineLevel = 1; 4expect(worksheet.getColumn(3).collapsed).to.be.true; 5 6worksheet.properties.outlineLevelCol = 2; 7expect(worksheet.getColumn(3).collapsed).to.be.false;
The outline properties can be set on the worksheet
1worksheet.properties.outlineProperties = { 2 summaryBelow: false, 3 summaryRight: false, 4};
Images
Adding images to a worksheet is a two-step process. First, the image is added to the workbook via the addImage() function which will also return an imageId value. Then, using the imageId, the image can be added to the worksheet either as a tiled background or covering a cell range.
Note: As of this version, adjusting or transforming the image is not supported.
Add Image to Workbook
The Workbook.addImage function supports adding images by filename or by Buffer. Note that in both cases, the extension must be specified. Valid extension values include 'jpeg', 'png', 'gif'.
1// add image to workbook by filename 2var imageId1 = workbook.addImage({ 3 filename: 'path/to/image.jpg', 4 extension: 'jpeg', 5}); 6 7// add image to workbook by buffer 8var imageId2 = workbook.addImage({ 9 buffer: fs.readFileSync('path/to.image.png'), 10 extension: 'png', 11}); 12 13// add image to workbook by base64 14var myBase64Image = "data:image/png;base64,iVBORw0KG..."; 15var imageId2 = workbook.addImage({ 16 base64: myBase64Image, 17 extension: 'png', 18});
Add image background to worksheet
Using the image id from Workbook.addImage, the background to a worksheet can be set using the addBackgroundImage function
1// set background 2worksheet.addBackgroundImage(imageId1);
Add image over a range
Using the image id from Workbook.addImage, an image can be embedded within the worksheet to cover a range. The coordinates calculated from the range will cover from the top-left of the first cell to the bottom right of the second.
1// insert an image over B2:D6 2worksheet.addImage(imageId2, 'B2:D6');
Using a structure instead of a range string, it is possible to partially cover cells.
Note that the coordinate system used for this is zero based, so the top-left of A1 will be { col: 0, row: 0 }. Fractions of cells can be specified by using floating point numbers, e.g. the midpoint of A1 is { col: 0.5, row: 0.5 }.
1// insert an image over part of B2:D6 2worksheet.addImage(imageId2, { 3 tl: { col: 1.5, row: 1.5 }, 4 br: { col: 3.5, row: 5.5 } 5});
The cell range can also have the eproperty 'editAs' which will control how the image is anchored to the cell(s) It can have one of the following values:
Value | Description |
---|---|
undefined | This is the default. It specifies the image will be moved and sized with cells |
oneCell | Image will be moved with cells but not sized |
absolute | Image will not be moved or sized with cells |
1ws.addImage(imageId, { 2 tl: { col: 0.1125, row: 0.4 }, 3 br: { col: 2.101046875, row: 3.4 }, 4 editAs: 'oneCell' 5});
Add image to a cell
You can add an image to a cell and then define its width and height in pixels at 96dpi.
1worksheet.addImage(imageId2, { 2 tl: { col: 0, row: 0 }, 3 ext: { width: 500, height: 200 } 4});
File I/O
XLSX
Reading XLSX
1// read from a file 2var workbook = new Excel.Workbook(); 3workbook.xlsx.readFile(filename) 4 .then(function() { 5 // use workbook 6 }); 7 8// pipe from stream 9var workbook = new Excel.Workbook(); 10stream.pipe(workbook.xlsx.createInputStream()); 11 12// load from buffer 13var workbook = new Excel.Workbook(); 14workbook.xlsx.load(data) 15 .then(function() { 16 // use workbook 17 });
Writing XLSX
1// write to a file 2var workbook = createAndFillWorkbook(); 3workbook.xlsx.writeFile(filename) 4 .then(function() { 5 // done 6 }); 7 8// write to a stream 9workbook.xlsx.write(stream) 10 .then(function() { 11 // done 12 }); 13 14// write to a new buffer 15workbook.xlsx.writeBuffer() 16 .then(function(buffer) { 17 // done 18 });
CSV
Reading CSV
1// read from a file 2var workbook = new Excel.Workbook(); 3workbook.csv.readFile(filename) 4 .then(worksheet => { 5 // use workbook or worksheet 6 }); 7 8// read from a stream 9var workbook = new Excel.Workbook(); 10workbook.csv.read(stream) 11 .then(worksheet => { 12 // use workbook or worksheet 13 }); 14 15// pipe from stream 16var workbook = new Excel.Workbook(); 17stream.pipe(workbook.csv.createInputStream()); 18 19// read from a file with European Dates 20var workbook = new Excel.Workbook(); 21var options = { 22 dateFormats: ['DD/MM/YYYY'] 23}; 24workbook.csv.readFile(filename, options) 25 .then(worksheet => { 26 // use workbook or worksheet 27 }); 28 29// read from a file with custom value parsing 30var workbook = new Excel.Workbook(); 31var options = { 32 map(value, index) { 33 switch(index) { 34 case 0: 35 // column 1 is string 36 return value; 37 case 1: 38 // column 2 is a date 39 return new Date(value); 40 case 2: 41 // column 3 is JSON of a formula value 42 return JSON.parse(value); 43 default: 44 // the rest are numbers 45 return parseFloat(value); 46 } 47 } 48}; 49workbook.csv.readFile(filename, options) 50 .then(function(worksheet) { 51 // use workbook or worksheet 52 });
The CSV parser uses fast-csv to read the CSV file. The options passed into the read functions above is also passed to fast-csv for parsing of the csv data. Please refer to the fast-csv README.md for details.
Dates are parsed using the npm module dayjs. If no dateFormats are supplied, the following are used:
- dayjs.ISO_8601
- 'MM-DD-YYYY'
- 'YYYY-MM-DD'
Writing CSV
1 2// write to a file 3var workbook = createAndFillWorkbook(); 4workbook.csv.writeFile(filename) 5 .then(() => { 6 // done 7 }); 8 9// write to a stream 10// Be careful that you need to provide sheetName or 11// sheetId for correct import to csv. 12workbook.csv.write(stream, { sheetName: 'Page name' }) 13 .then(() => { 14 // done 15 }); 16 17// write to a file with European Date-Times 18var workbook = new Excel.Workbook(); 19var options = { 20 dateFormat: 'DD/MM/YYYY HH:mm:ss', 21 dateUTC: true, // use utc when rendering dates 22}; 23workbook.csv.writeFile(filename, options) 24 .then(() => { 25 // done 26 }); 27 28 29// write to a file with custom value formatting 30var workbook = new Excel.Workbook(); 31var options = { 32 map(value, index) { 33 switch(index) { 34 case 0: 35 // column 1 is string 36 return value; 37 case 1: 38 // column 2 is a date 39 return dayjs(value).format('YYYY-MM-DD'); 40 case 2: 41 // column 3 is a formula, write just the result 42 return value.result; 43 default: 44 // the rest are numbers 45 return value; 46 } 47 } 48}; 49workbook.csv.writeFile(filename, options) 50 .then(() => { 51 // done 52 }); 53 54// write to a new buffer 55workbook.csv.writeBuffer() 56 .then(function(buffer) { 57 // done 58 });
The CSV parser uses fast-csv to write the CSV file. The options passed into the write functions above is also passed to fast-csv for writing the csv data. Please refer to the fast-csv README.md for details.
Dates are formatted using the npm module dayjs.
If no dateFormat is supplied, moment.ISO_8601 is used.
When writing a CSV you can supply the boolean dateUTC as true to have ExcelJS parse the date without automatically
converting the timezone using moment.utc()
.
Streaming I/O
The File I/O documented above requires that an entire workbook is built up in memory before the file can be written. While convenient, it can limit the size of the document due to the amount of memory required.
A streaming writer (or reader) processes the workbook or worksheet data as it is generated, converting it into file form as it goes. Typically this is much more efficient on memory as the final memory footprint and even intermediate memory footprints are much more compact than with the document version, especially when you consider that the row and cell objects are disposed once they are committed.
The interface to the streaming workbook and worksheet is almost the same as the document versions with a few minor practical differences:
- Once a worksheet is added to a workbook, it cannot be removed.
- Once a row is committed, it is no longer accessible since it will have been dropped from the worksheet.
- unMergeCells() is not supported.
Note that it is possible to build the entire workbook without committing any rows. When the workbook is committed, all added worksheets (including all uncommitted rows) will be automatically committed. However in this case, little will have been gained over the Document version.
Streaming XLSX
Streaming XLSX Writer
The streaming XLSX writer is available in the ExcelJS.stream.xlsx namespace.
The constructor takes an optional options object with the following fields:
Field | Description |
---|---|
stream | Specifies a writable stream to write the XLSX workbook to. |
filename | If stream not specified, this field specifies the path to a file to write the XLSX workbook to. |
useSharedStrings | Specifies whether to use shared strings in the workbook. Default is false |
useStyles | Specifies whether to add style information to the workbook. Styles can add some performance overhead. Default is false |
If neither stream nor filename is specified in the options, the workbook writer will create a StreamBuf object that will store the contents of the XLSX workbook in memory. This StreamBuf object, which can be accessed via the property workbook.stream, can be used to either access the bytes directly by stream.read() or to pipe the contents to another stream.
1// construct a streaming XLSX workbook writer with styles and shared strings 2var options = { 3 filename: './streamed-workbook.xlsx', 4 useStyles: true, 5 useSharedStrings: true 6}; 7var workbook = new Excel.stream.xlsx.WorkbookWriter(options);
In general, the interface to the streaming XLSX writer is the same as the Document workbook (and worksheets) described above, in fact the row, cell and style objects are the same.
However there are some differences...
Construction
As seen above, the WorkbookWriter will typically require the output stream or file to be specified in the constructor.
Committing Data
When a worksheet row is ready, it should be committed so that the row object and contents can be freed. Typically this would be done as each row is added...
1worksheet.addRow({ 2 id: i, 3 name: theName, 4 etc: someOtherDetail 5}).commit();
The reason the WorksheetWriter does not commit rows as they are added is to allow cells to be merged across rows:
1worksheet.mergeCells('A1:B2'); 2worksheet.getCell('A1').value = 'I am merged'; 3worksheet.getCell('C1').value = 'I am not'; 4worksheet.getCell('C2').value = 'Neither am I'; 5worksheet.getRow(2).commit(); // now rows 1 and two are committed.
As each worksheet is completed, it must also be committed:
1// Finished adding data. Commit the worksheet 2worksheet.commit();
To complete the XLSX document, the workbook must be committed. If any worksheet in a workbook are uncommitted, they will be committed automatically as part of the workbook commit.
1// Finished the workbook. 2workbook.commit() 3 .then(function() { 4 // the stream has been written 5 });
Browser
A portion of this library has been isolated and tested for use within a browser environment.
Due to the streaming nature of the workbook reader and workbook writer, these have not been included. Only the document based workbook may be used (see Create a Workbook for details).
For example code using ExcelJS in the browser take a look at the spec/browser folder in the github repo.
Prebundled
The following files are pre-bundled and included inside the dist folder.
- exceljs.js
- exceljs.min.js
Value Types
The following value types are supported.
Null Value
Enum: Excel.ValueType.Null
A null value indicates an absence of value and will typically not be stored when written to file (except for merged cells). It can be used to remove the value from a cell.
E.g.
1worksheet.getCell('A1').value = null;
Merge Cell
Enum: Excel.ValueType.Merge
A merge cell is one that has its value bound to another 'master' cell. Assigning to a merge cell will cause the master's cell to be modified.
Number Value
Enum: Excel.ValueType.Number
A numeric value.
E.g.
1worksheet.getCell('A1').value = 5; 2worksheet.getCell('A2').value = 3.14159;
String Value
Enum: Excel.ValueType.String
A simple text string.
E.g.
1worksheet.getCell('A1').value = 'Hello, World!';
Date Value
Enum: Excel.ValueType.Date
A date value, represented by the JavaScript Date type.
E.g.
1worksheet.getCell('A1').value = new Date(2017, 2, 15);
Hyperlink Value
Enum: Excel.ValueType.Hyperlink
A URL with both text and link value.
E.g.
1// link to web 2worksheet.getCell('A1').value = { 3 text: 'www.mylink.com', 4 hyperlink: 'http://www.mylink.com', 5 tooltip: 'www.mylink.com' 6}; 7 8// internal link 9worksheet.getCell('A1').value = { text: 'Sheet2', hyperlink: '#\\"Sheet2\\"!A1' };
Formula Value
Enum: Excel.ValueType.Formula
An Excel formula for calculating values on the fly. Note that while the cell type will be Formula, the cell may have an effectiveType value that will be derived from the result value.
Note that ExcelJS cannot process the formula to generate a result, it must be supplied.
E.g.
1worksheet.getCell('A3').value = { formula: 'A1+A2', result: 7 };
Cells also support convenience getters to access the formula and result:
1worksheet.getCell('A3').formula === 'A1+A2'; 2worksheet.getCell('A3').result === 7;
Shared Formula
Shared formulae enhance the compression of the xlsx document by increasing the repetition of text within the worksheet xml.
A shared formula can be assigned to a cell using a new value form:
1worksheet.getCell('B3').value = { sharedFormula: 'A3', result: 10 };
This specifies that the cell B3 is a formula that will be derived from the formula in A3 and its result is 10.
The formula convenience getter will translate the formula in A3 to what it should be in B3:
1worksheet.getCell('B3').formula === 'B1+B2';
Formula Type
To distinguish between real and translated formula cells, use the formulaType getter:
1worksheet.getCell('A3').formulaType === Enums.FormulaType.Master; 2worksheet.getCell('B3').formulaType === Enums.FormulaType.Shared;
Formula type has the following values:
Name | Value |
---|---|
Enums.FormulaType.None | 0 |
Enums.FormulaType.Master | 1 |
Enums.FormulaType.Shared | 2 |
Rich Text Value
Enum: Excel.ValueType.RichText
Rich, styled text.
E.g.
1worksheet.getCell('A1').value = { 2 richText: [ 3 { text: 'This is '}, 4 {font: {italic: true}, text: 'italic'}, 5 ] 6};
Boolean Value
Enum: Excel.ValueType.Boolean
E.g.
1worksheet.getCell('A1').value = true; 2worksheet.getCell('A2').value = false;
Error Value
Enum: Excel.ValueType.Error
E.g.
1worksheet.getCell('A1').value = { error: '#N/A' }; 2worksheet.getCell('A2').value = { error: '#VALUE!' };
The current valid Error text values are:
Name | Value |
---|---|
Excel.ErrorValue.NotApplicable | #N/A |
Excel.ErrorValue.Ref | #REF! |
Excel.ErrorValue.Name | #NAME? |
Excel.ErrorValue.DivZero | #DIV/0! |
Excel.ErrorValue.Null | #NULL! |
Excel.ErrorValue.Value | #VALUE! |
Excel.ErrorValue.Num | #NUM! |
Interface Changes
Every effort is made to make a good consistent interface that doesn't break through the versions but regrettably, now and then some things have to change for the greater good.
0.1.0
Worksheet.eachRow
The arguments in the callback function to Worksheet.eachRow have been swapped and changed; it was function(rowNumber,rowValues), now it is function(row, rowNumber) which gives it a look and feel more like the underscore (_.each) function and prioritises the row object over the row number.
Worksheet.getRow
This function has changed from returning a sparse array of cell values to returning a Row object. This enables accessing row properties and will facilitate managing row styles and so on.
The sparse array of cell values is still available via Worksheet.getRow(rowNumber).values;
0.1.1
cell.model
cell.styles renamed to cell.style
0.2.44
Promises returned from functions switched from Bluebird to native node Promise which can break calling code if they rely on Bluebird's extra features.
To mitigate this the following two changes were added to 0.3.0:
- A more fully featured and still browser compatable promise lib is used by default. This lib supports many of the features of Bluebird but with a much lower footprint.
- An option to inject a different Promise implementation. See Config section for more details.
Config
ExcelJS now supports dependency injection for the promise library. You can restore Bluebird promises by including the following code in your module...
1ExcelJS.config.setValue('promise', require('bluebird'));
Please note: I have tested ExcelJS with bluebird specifically (since up until recently this was the library it used). From the tests I have done it will not work with Q.
Caveats
Dist Folder
Before publishing this module, the source code is transpiled and otherwise processed before being placed in a dist/ folder. This README identifies two files - a browserified bundle and minified version. No other contents of the dist/ folder are guaranteed in any way other than the file specified as "main" in the package.json
Known Issues
Testing with Puppeteer
The test suite included in this lib includes a small script executed in a headless browser to validate the bundled packages. At the time of this writing, it appears that this test does not play nicely in the Windows Linux subsystem.
For this reason, the browser test can be disabled by the existence of a file named .disable-test-browser
1sudo apt-get install libfontconfig
Splice vs Merge
If any splice operation affects a merged cell, the merge group will not be moved correctly
Release History
Version | Changes |
---|---|
0.0.9 | |
0.1.0 |
|
0.1.1 |
|
0.1.2 |
|
0.1.3 |
|
0.1.5 |
|
0.1.6 |
|
0.1.8 |
|
0.1.9 |
|
0.1.10 |
|
0.1.11 |
|
0.2.0 |
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
Found 0/27 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 6 are checked with a SAST tool
Score
3
/10
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More