ExcelJS
Read, manipulate and write spreadsheet data and styles to XLSX and JSON.
Reverse engineered from Excel spreadsheet files as a project.
Installation
npm install exceljs
New Features!
Contributions
Contributions are very welcome! It helps me know what features are desired or what bugs are causing the most pain.
I have just one request; If you submit a pull request for a bugfix, please add a unit-test or integration-test (in the spec folder) that catches the problem.
Even a PR that just has a failing test is fine - I can analyse what the test is doing and fix the code from that.
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
Importing
The default export is a transpiled ES5 version with a Promise polyfill - this offers the highest level of compatibility.
var Excel = require('exceljs');
import Excel from 'exceljs';
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:
const Excel = require('exceljs/modern.nodejs');
import Excel from 'exceljs/modern.browser';
Create a Workbook
var workbook = new Excel.Workbook();
Set Workbook Properties
workbook.creator = 'Me';
workbook.lastModifiedBy = 'Her';
workbook.created = new Date(1985, 8, 30);
workbook.modified = new Date();
workbook.lastPrinted = new Date(2016, 9, 27);
workbook.properties.date1904 = true;
Workbook Views
The Workbook views controls how many separate windows Excel will open when viewing the workbook.
workbook.views = [
{
x: 0, y: 0, width: 10000, height: 20000,
firstSheet: 0, activeTab: 1, visibility: 'visible'
}
]
Add a Worksheet
var sheet = workbook.addWorksheet('My Sheet');
Use the second parameter of the addWorksheet function to specify options for the worksheet.
For Example:
var sheet = workbook.addWorksheet('My Sheet', {properties:{tabColor:{argb:'FFC0000'}}});
var sheet = workbook.addWorksheet('My Sheet', {properties: {showGridLines: false}});
var 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:
var sheet = workbook.addWorksheet('My Sheet');
workbook.removeWorksheet(sheet.id)
Access Worksheets
workbook.eachSheet(function(worksheet, sheetId) {
});
var worksheet = workbook.getWorksheet('My Sheet');
var worksheet = workbook.getWorksheet(1);
Worksheet State
worksheet.state = 'visible';
worksheet.state = 'hidden';
worksheet.state = 'veryHidden';
Worksheet Properties
Worksheets support a property bucket to allow control over some features of the worksheet.
var worksheet = workbook.addWorksheet('sheet', {properties:{tabColor:{argb:'FF00FF00'}}});
var worksheetWriter = workbookWriter.addSheet('sheet', {properties:{outlineLevelCol:1}});
worksheet.properties.outlineLevelCol = 2;
worksheet.properties.defaultRowHeight = 15;
Supported Properties
Name | Default | Description |
---|
tabColor | undefined | Color of the tabs |
outlineLevelCol | 0 | The worksheet column outline level |
outlineLevelRow | 0 | The worksheet row outline level |
defaultRowHeight | 15 | Default row height |
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.
var worksheet = workbook.addWorksheet('sheet', {
pageSetup:{paperSize: 9, orientation:'landscape'}
});
var worksheetWriter = workbookWriter.addSheet('sheet', {
pageSetup:{fitToPage: true, fitToHeight: 5, fitToWidth: 7}
});
worksheet.pageSetup.margins = {
left: 0.7, right: 0.7,
top: 0.75, bottom: 0.75,
header: 0.3, footer: 0.3
};
worksheet.pageSetup.printArea = 'A1:G20';
worksheet.pageSetup.printTitlesRow = '1:3';
worksheet.pageSetup.printTitlesColumn = 'A:C';
Supported pageSetup settings
Name | Default | Description |
---|
margins | | Whitespace on the borders of the page. Units are inches. |
orientation | 'portrait' | Orientation of the page - i.e. taller (portrait) or wider (landscape) |
horizontalDpi | 4294967295 | Horizontal Dots per Inch. Default value is -1 |
verticalDpi | 4294967295 | Vertical Dots per Inch. Default value is -1 |
fitToPage | | Whether to use fitToWidth and fitToHeight or scale settings. Default is based on presence of these settings in the pageSetup object - if both are present, scale wins (i.e. default will be false) |
pageOrder | 'downThenOver' | Which order to print the pages - one of ['downThenOver', 'overThenDown'] |
blackAndWhite | false | Print without colour |
draft | false | Print with less quality (and ink) |
cellComments | 'None' | Where to place comments - one of ['atEnd', 'asDisplayed', 'None'] |
errors | 'displayed' | Where to show errors - one of ['dash', 'blank', 'NA', 'displayed'] |
scale | 100 | Percentage value to increase or reduce the size of the print. Active when fitToPage is false |
fitToWidth | 1 | How many pages wide the sheet should print on to. Active when fitToPage is true |
fitToHeight | 1 | How many pages high the sheet should print on to. Active when fitToPage is true |
paperSize | | What paper size to use (see below) |
showRowColHeaders | false | Whether to show the row numbers and column letters |
showGridLines | false | Whether to show grid lines |
firstPageNumber | | Which number to use for the first page |
horizontalCentered | false | Whether to center the sheet data horizontally |
verticalCentered | false | Whether to center the sheet data vertically |
Example Paper Sizes
Name | Value |
---|
Letter | undefined |
Legal | 5 |
Executive | 7 |
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 |
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 |
worksheet.views = [
{state: 'frozen', xSplit: 2, ySplit: 3, topLeftCell: 'G10', activeCell: 'A1'}
];
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 |
worksheet.views = [
{state: 'split', xSplit: 2000, ySplit: 3000, topLeftCell: 'G10', activeCell: 'A1'}
];
Auto filters
It is possible to apply an auto filter to your worksheet.
worksheet.autoFilter = 'A1:C1';
While the range string is the standard form of the autoFilter, the worksheet will also support the
following values:
worksheet.autoFilter = {
from: 'A1',
to: 'C1',
}
worksheet.autoFilter = {
from: {
row: 3,
column: 1
},
to: {
row: 5,
column: 12
}
}
worksheet.autoFilter = {
from: 'D3',
to: {
row: 7,
column: 5
}
}
Columns
worksheet.columns = [
{ header: 'Id', key: 'id', width: 10 },
{ header: 'Name', key: 'name', width: 32 },
{ header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 }
];
var idCol = worksheet.getColumn('id');
var nameCol = worksheet.getColumn('B');
var dobCol = worksheet.getColumn(3);
dobCol.header = 'Date of Birth';
dobCol.header = ['Date of Birth', 'A.K.A. D.O.B.'];
dobCol.key = 'dob';
dobCol.width = 15;
dobCol.hidden = true;
worksheet.getColumn(4).outlineLevel = 0;
worksheet.getColumn(5).outlineLevel = 1;
expect(worksheet.getColumn(4).collapsed).to.equal(false);
expect(worksheet.getColumn(5).collapsed).to.equal(true);
dobCol.eachCell(function(cell, rowNumber) {
});
dobCol.eachCell({ includeEmpty: true }, function(cell, rowNumber) {
});
worksheet.getColumn(6).values = [1,2,3,4,5];
worksheet.getColumn(7).values = [,,2,3,,5,,7,,,,11];
worksheet.spliceColumns(3,2);
var newCol3Values = [1,2,3,4,5];
var newCol4Values = ['one', 'two', 'three', 'four', 'five'];
worksheet.spliceColumns(3, 1, newCol3Values, newCol4Values);
Rows
worksheet.addRow({id: 1, name: 'John Doe', dob: new Date(1970,1,1)});
worksheet.addRow({id: 2, name: 'Jane Doe', dob: new Date(1965,1,7)});
worksheet.addRow([3, 'Sam', new Date()]);
var rowValues = [];
rowValues[1] = 4;
rowValues[5] = 'Kyle';
rowValues[9] = new Date();
worksheet.addRow(rowValues);
var rows = [
[5,'Bob',new Date()],
{id:6, name: 'Barbara', dob: new Date()}
];
worksheet.addRows(rows);
var row = worksheet.getRow(5);
var row = worksheet.lastRow;
row.height = 42.5;
row.hidden = true;
worksheet.getRow(4).outlineLevel = 0;
worksheet.getRow(5).outlineLevel = 1;
expect(worksheet.getRow(4).collapsed).to.equal(false);
expect(worksheet.getRow(5).collapsed).to.equal(true);
row.getCell(1).value = 5;
row.getCell('name').value = 'Zeb';
row.getCell('C').value = new Date();
row = worksheet.getRow(4).values;
expect(row[5]).toEqual('Kyle');
row.values = [1,2,3];
expect(row.getCell(1).value).toEqual(1);
expect(row.getCell(2).value).toEqual(2);
expect(row.getCell(3).value).toEqual(3);
var values = []
values[5] = 7;
values[10] = 'Hello, World!';
row.values = values;
expect(row.getCell(1).value).toBeNull();
expect(row.getCell(5).value).toEqual(7);
expect(row.getCell(10).value).toEqual('Hello, World!');
row.values = {
id: 13,
name: 'Thing 1',
dob: new Date()
};
row.addPageBreak();
worksheet.eachRow(function(row, rowNumber) {
console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));
});
worksheet.eachRow({ includeEmpty: true }, function(row, rowNumber) {
console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));
});
row.eachCell(function(cell, colNumber) {
console.log('Cell ' + colNumber + ' = ' + cell.value);
});
row.eachCell({ includeEmpty: true }, function(cell, colNumber) {
console.log('Cell ' + colNumber + ' = ' + cell.value);
});
worksheet.spliceRows(4,3);
var newRow3Values = [1,2,3,4,5];
var newRow4Values = ['one', 'two', 'three', 'four', 'five'];
worksheet.spliceRows(3, 1, newRow3Values, newRow4Values);
row.splice(3,2);
row.splice(4,1,'new value 1', 'new value 2');
row.commit();
var rowSize = row.cellCount;
var numValues = row.actualCellCount;
Handling Individual Cells
var cell = worksheet.getCell('C3');
cell.value = new Date(1968, 5, 1);
expect(cell.type).toEqual(Excel.ValueType.Date);
myInput.value = cell.text;
var html = '<div>' + cell.html + '</div>';
Merged Cells
worksheet.mergeCells('A4:B5');
worksheet.getCell('B5').value = 'Hello, World!';
expect(worksheet.getCell('B5').value).toBe(worksheet.getCell('A4').value);
expect(worksheet.getCell('B5').master).toBe(worksheet.getCell('A4'));
expect(worksheet.getCell('B5').style).toBe(worksheet.getCell('A4').style);
worksheet.getCell('B5').style.font = myFonts.arial;
expect(worksheet.getCell('A4').style.font).toBe(myFonts.arial);
worksheet.unMergeCells('A4');
expect(worksheet.getCell('B5').style).not.toBe(worksheet.getCell('A4').style);
expect(worksheet.getCell('B5').style.font).not.toBe(myFonts.arial);
worksheet.mergeCells('G10', 'H11');
worksheet.mergeCells(10,11,12,13);
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).
worksheet.getCell('A1').name = 'PI';
expect(worksheet.getCell('A1').name).to.equal('PI');
worksheet.getCell('A1').names = ['thing1', 'thing2'];
expect(worksheet.getCell('A1').names).to.have.members(['thing1', 'thing2']);
worksheet.getCell('A1').removeName('thing1');
expect(worksheet.getCell('A1').names).to.have.members(['thing2']);
Data Validations
Cells can define what values are valid or not and provide prompting to the user to help guide them.
Validation types can be one of the following:
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 |
worksheet.getCell('A1').dataValidation = {
type: 'list',
allowBlank: true,
formulae: ['"One,Two,Three,Four"']
};
worksheet.getCell('A1').dataValidation = {
type: 'list',
allowBlank: true,
formulae: ['$D$5:$F$5']
};
worksheet.getCell('A1').dataValidation = {
type: 'whole',
operator: 'notEqual',
showErrorMessage: true,
formulae: [5],
errorStyle: 'error',
errorTitle: 'Five',
error: 'The value must not be Five'
};
worksheet.getCell('A1').dataValidation = {
type: 'decimal',
operator: 'between',
allowBlank: true,
showInputMessage: true,
formulae: [1.5, 7],
promptTitle: 'Decimal',
prompt: 'The value must between 1.5 and 7'
};
worksheet.getCell('A1').dataValidation = {
type: 'textLength',
operator: 'lessThan',
showErrorMessage: true,
allowBlank: true,
formulae: [15]
};
worksheet.getCell('A1').dataValidation = {
type: 'date',
operator: 'lessThan',
showErrorMessage: true,
allowBlank: true,
formulae: [new Date(2016,0,1)]
};
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:
ws.getCell('A1').numFmt = '0.00%';
ws.columns = [
{ header: 'Id', key: 'id', width: 10 },
{ header: 'Name', key: 'name', width: 32, style: { font: { name: 'Arial Black' } } },
{ header: 'D.O.B.', key: 'DOB', width: 10, style: { numFmt: 'dd/mm/yyyy' } }
];
ws.getColumn(3).numFmt = '"£"#,##0.00;[Red]\-"£"#,##0.00';
ws.getRow(2).font = { name: 'Comic Sans MS', family: 4, size: 16, underline: 'double', bold: true };
When a style is applied to a row or column, it will be applied to all currently existing cells in that row or column.
Also, any new cell that is created will inherit its initial styles from the row and column it belongs to.
If a cell's row and column both define a specific style (e.g. font), the cell will use the row style over the column style.
However if the row and column define different styles (e.g. column.numFmt and row.font), the cell will inherit the font from the row and the numFmt from the column.
Caveat: All the above properties (with the exception of numFmt, which is a string), are JS object structures.
If the same style object is assigned to more than one spreadsheet entity, then each entity will share the same style object.
If the style object is later modified before the spreadsheet is serialized, then all entities referencing that style object will be modified too.
This behaviour is intended to prioritize performance by reducing the number of JS objects created.
If you want the style objects to be independent, you will need to clone them before assigning them.
Also, by default, when a document is read from file (or stream) if spreadsheet entities share similar styles, then they will reference the same style object too.
Number Formats
ws.getCell('A1').value = 1.6;
ws.getCell('A1').numFmt = '# ?/?';
ws.getCell('B1').value = 0.016;
ws.getCell('B1').numFmt = '0.00%';
Fonts
ws.getCell('A1').font = {
name: 'Comic Sans MS',
family: 4,
size: 16,
underline: true,
bold: true
};
ws.getCell('A2').font = {
name: 'Arial Black',
color: { argb: 'FF00FF00' },
family: 2,
size: 14,
italic: true
};
ws.getCell('A3').font = {
vertAlign: 'superscript'
};
var font = { name: 'Arial', size: 12 };
ws.getCell('A3').font = font;
font.size = 20;
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 strikethrough | true, false |
outline | Font outline | true, false |
vertAlign | Vertical align | 'superscript', 'subscript' |
Alignment
ws.getCell('A1').alignment = { vertical: 'top', horizontal: 'left' };
ws.getCell('B1').alignment = { vertical: 'middle', horizontal: 'center' };
ws.getCell('C1').alignment = { vertical: 'bottom', horizontal: 'right' };
ws.getCell('D1').alignment = { wrapText: true };
ws.getCell('E1').alignment = { indent: 1 };
ws.getCell('F1').alignment = { textRotation: 30 };
ws.getCell('G1').alignment = { textRotation: -45 };
ws.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
ws.getCell('A1').border = {
top: {style:'thin'},
left: {style:'thin'},
bottom: {style:'thin'},
right: {style:'thin'}
};
ws.getCell('A3').border = {
top: {style:'double', color: {argb:'FF00FF00'}},
left: {style:'double', color: {argb:'FF00FF00'}},
bottom: {style:'double', color: {argb:'FF00FF00'}},
right: {style:'double', color: {argb:'FF00FF00'}}
};
ws.getCell('A5').border = {
diagonal: {up: true, down: true, style:'thick', color: {argb:'FFFF0000'}}
};
Valid Border Styles
- thin
- dotted
- dashDot
- hair
- dashDotDot
- slantDashDot
- mediumDashed
- mediumDashDotDot
- mediumDashDot
- medium
- double
- thick
Fills
ws.getCell('A1').fill = {
type: 'pattern',
pattern:'darkVertical',
fgColor:{argb:'FFFF0000'}
};
ws.getCell('A2').fill = {
type: 'pattern',
pattern:'darkTrellis',
fgColor:{argb:'FFFFFF00'},
bgColor:{argb:'FF0000FF'}
};
ws.getCell('A3').fill = {
type: 'gradient',
gradient: 'angle',
degree: 0,
stops: [
{position:0, color:{argb:'FF0000FF'}},
{position:0.5, color:{argb:'FFFFFFFF'}},
{position:1, color:{argb:'FF0000FF'}}
]
};
ws.getCell('A2').fill = {
type: 'gradient',
gradient: 'path',
center:{left:0.5,top:0.5},
stops: [
{position:0, color:{argb:'FFFF0000'}},
{position:1, color:{argb:'FF00FF00'}}
]
};
Pattern Fills
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.
ws.getCell('A1').value = {
'richText': [
{'font': {'size': 12,'color': {'theme': 0},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': 'This is '},
{'font': {'italic': true,'size': 12,'color': {'theme': 0},'name': 'Calibri','scheme': 'minor'},'text': 'a'},
{'font': {'size': 12,'color': {'theme': 1},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': ' '},
{'font': {'size': 12,'color': {'argb': 'FFFF6600'},'name': 'Calibri','scheme': 'minor'},'text': 'colorful'},
{'font': {'size': 12,'color': {'theme': 1},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': ' text '},
{'font': {'size': 12,'color': {'argb': 'FFCCFFCC'},'name': 'Calibri','scheme': 'minor'},'text': 'with'},
{'font': {'size': 12,'color': {'theme': 1},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': ' in-cell '},
{'font': {'bold': true,'size': 12,'color': {'theme': 1},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': 'format'}
]
};
expect(ws.getCell('A1').text).to.equal('This is a colorful text with in-cell format');
expect(ws.getCell('A1').type).to.equal(Excel.ValueType.RichText);
Outline Levels
Excel supports outlining; where rows or columns can be expanded or collapsed depending on what level of detail the user wishes to view.
Outline levels can be defined in column setup:
worksheet.columns = [
{ header: 'Id', key: 'id', width: 10 },
{ header: 'Name', key: 'name', width: 32 },
{ header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 }
];
Or directly on the row or column
worksheet.getColumn(3).outlineLevel = 1;
worksheet.getRow(3).outlineLevel = 1;
The sheet outline levels can be set on the worksheet
worksheet.properties.outlineLevelCol = 1;
worksheet.properties.outlineLevelRow = 1;
Note: adjusting outline levels on rows or columns or the outline levels on the worksheet will incur a side effect of also modifying the collapsed property of all rows or columns affected by the property change. E.g.:
worksheet.properties.outlineLevelCol = 1;
worksheet.getColumn(3).outlineLevel = 1;
expect(worksheet.getColumn(3).collapsed).to.be.true;
worksheet.properties.outlineLevelCol = 2;
expect(worksheet.getColumn(3).collapsed).to.be.false;
The outline properties can be set on the worksheet
worksheet.properties.outlineProperties = {
summaryBelow: false,
summaryRight: false,
};
Images
Adding images to a worksheet is a two-step process.
First, the image is added to the workbook via the addImage() function which will also return an imageId value.
Then, using the imageId, the image can be added to the worksheet either as a tiled background or covering a cell range.
Note: As of this version, adjusting or transforming the image is not supported.
Add Image to Workbook
The Workbook.addImage function supports adding images by filename or by Buffer.
Note that in both cases, the extension must be specified.
Valid extension values include 'jpeg', 'png', 'gif'.
var imageId1 = workbook.addImage({
filename: 'path/to/image.jpg',
extension: 'jpeg',
});
var imageId2 = workbook.addImage({
buffer: fs.readFileSync('path/to.image.png'),
extension: 'png',
});
var myBase64Image = "data:image/png;base64,iVBORw0KG...";
var imageId2 = workbook.addImage({
base64: myBase64Image,
extension: 'png',
});
Add image background to worksheet
Using the image id from Workbook.addImage, the background to a worksheet can be set using the addBackgroundImage function
worksheet.addBackgroundImage(imageId1);
Add image over a range
Using the image id from Workbook.addImage, an image can be embedded within the worksheet to cover a range.
The coordinates calculated from the range will cover from the top-left of the first cell to the bottom right of the second.
worksheet.addImage(imageId2, 'B2:D6');
Using a structure instead of a range string, it is possible to partially cover cells.
Note that the coordinate system used for this is zero based, so the top-left of A1 will be { col: 0, row: 0 }.
Fractions of cells can be specified by using floating point numbers, e.g. the midpoint of A1 is { col: 0.5, row: 0.5 }.
worksheet.addImage(imageId2, {
tl: { col: 1.5, row: 1.5 },
br: { col: 3.5, row: 5.5 }
});
The cell range can also have the eproperty 'editAs' which will control how the image is anchored to the cell(s)
It can have one of the following values:
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 |
ws.addImage(imageId, {
tl: { col: 0.1125, row: 0.4 },
br: { col: 2.101046875, row: 3.4 },
editAs: 'oneCell'
});
Add image to a cell
You can add an image to a cell and then define its width and height in pixels at 96dpi.
worksheet.addImage(imageId2, {
tl: { col: 0, row: 0 },
ext: { width: 500, height: 200 }
});
File I/O
XLSX
Reading XLSX
var workbook = new Excel.Workbook();
workbook.xlsx.readFile(filename)
.then(function() {
});
var workbook = new Excel.Workbook();
stream.pipe(workbook.xlsx.createInputStream());
var workbook = new Excel.Workbook();
workbook.xlsx.load(data)
.then(function() {
});
Writing XLSX
var workbook = createAndFillWorkbook();
workbook.xlsx.writeFile(filename)
.then(function() {
});
workbook.xlsx.write(stream)
.then(function() {
});
CSV
Reading CSV
var workbook = new Excel.Workbook();
workbook.csv.readFile(filename)
.then(function(worksheet) {
});
var workbook = new Excel.Workbook();
workbook.csv.read(stream)
.then(function(worksheet) {
});
var workbook = new Excel.Workbook();
stream.pipe(workbook.csv.createInputStream());
var workbook = new Excel.Workbook();
var options = {
dateFormats: ['DD/MM/YYYY']
};
workbook.csv.readFile(filename, options)
.then(function(worksheet) {
});
var workbook = new Excel.Workbook();
var options = {
map: function(value, index) {
switch(index) {
case 0:
return value;
case 1:
return new Date(value);
case 2:
return JSON.parse(value);
default:
return parseFloat(value);
}
}
};
workbook.csv.readFile(filename, options)
.then(function(worksheet) {
});
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 moment.
If no dateFormats are supplied, the following are used:
- moment.ISO_8601
- 'MM-DD-YYYY'
- 'YYYY-MM-DD'
Writing CSV
var workbook = createAndFillWorkbook();
workbook.csv.writeFile(filename)
.then(function() {
});
workbook.csv.write(stream, { sheetName: 'Page name' })
.then(function() {
});
var workbook = new Excel.Workbook();
var options = {
dateFormat: 'DD/MM/YYYY HH:mm:ss',
dateUTC: true,
};
workbook.csv.readFile(filename, options)
.then(function(worksheet) {
});
var workbook = new Excel.Workbook();
var options = {
map: function(value, index) {
switch(index) {
case 0:
return value;
case 1:
return moment(value).format('YYYY-MM-DD');
case 2:
return value.result;
default:
return value;
}
}
};
workbook.csv.readFile(filename, options)
.then(function(worksheet) {
});
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 moment.
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.
var options = {
filename: './streamed-workbook.xlsx',
useStyles: true,
useSharedStrings: true
};
var 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...
worksheet.addRow({
id: i,
name: theName,
etc: someOtherDetail
}).commit();
The reason the WorksheetWriter does not commit rows as they are added is to allow cells to be merged across rows:
worksheet.mergeCells('A1:B2');
worksheet.getCell('A1').value = 'I am merged';
worksheet.getCell('C1').value = 'I am not';
worksheet.getCell('C2').value = 'Neither am I';
worksheet.getRow(2).commit();
As each worksheet is completed, it must also be committed:
worksheet.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.
workbook.commit()
.then(function() {
});
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 Worbook 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.
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.
worksheet.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.
worksheet.getCell('A1').value = 5;
worksheet.getCell('A2').value = 3.14159;
String Value
Enum: Excel.ValueType.String
A simple text string.
E.g.
worksheet.getCell('A1').value = 'Hello, World!';
Date Value
Enum: Excel.ValueType.Date
A date value, represented by the JavaScript Date type.
E.g.
worksheet.getCell('A1').value = new Date(2017, 2, 15);
Hyperlink Value
Enum: Excel.ValueType.Hyperlink
A URL with both text and link value.
E.g.
worksheet.getCell('A1').value = {
text: 'www.mylink.com',
hyperlink: 'http://www.mylink.com',
tooltip: 'www.mylink.com'
};
worksheet.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.
worksheet.getCell('A3').value = { formula: 'A1+A2', result: 7 };
Cells also support convenience getters to access the formula and result:
worksheet.getCell('A3').formula === 'A1+A2';
worksheet.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:
worksheet.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:
worksheet.getCell('B3').formula === 'B1+B2';
Formula Type
To distinguish between real and translated formula cells, use the formulaType getter:
worksheet.getCell('A3').formulaType === Enums.FormulaType.Master;
worksheet.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.
worksheet.getCell('A1').value = {
richText: [
{ text: 'This is '},
{font: {italic: true}, text: 'italic'},
]
};
Boolean Value
Enum: Excel.ValueType.Boolean
E.g.
worksheet.getCell('A1').value = true;
worksheet.getCell('A2').value = false;
Error Value
Enum: Excel.ValueType.Error
E.g.
worksheet.getCell('A1').value = { error: '#N/A' };
worksheet.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...
ExcelJS.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
sudo 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 | - Bug Fixes
- More textual data written properly to xml (including text, hyperlinks, formula results and format codes)
- Better date format code recognition
- Cell Font Style
|
0.1.2 | - Fixed potential race condition on zip write
|
0.1.3 | |
0.1.5 | - Bug Fixes
- Now handles 10 or more worksheets in one workbook
- theme1.xml file properly added and referenced
- Cell Borders
|
0.1.6 | - Bug Fixes
- More compatable theme1.xml included in XLSX file
- Cell Fills
|
0.1.8 | - Bug Fixes
- More compatable theme1.xml included in XLSX file
- Fixed filename case issue
- Cell Fills
|
0.1.9 | - Bug Fixes
- Added docProps files to satisfy Mac Excel users
- Fixed filename case issue
- Fixed worksheet id issue
- Core Workbook Properties
|
0.1.10 | - Bug Fixes
- Handles File Not Found error
- CSV Files
|
0.1.11 | |
0.2.0 | - Streaming XLSX Writer
- At long last ExcelJS can support writing massive XLSX files in a scalable memory efficient manner. Performance has been optimised and even smaller spreadsheets can be faster to write than the document writer. Options have been added to control the use of shared strings and styles as these can both have a considerable effect on performance
- Worksheet.lastRow
- Access the last editable row in a worksheet.
- Row.commit()
- For streaming writers, this method commits the row (and any previous rows) to the stream. Committed rows will no longer be editable (and are typically deleted from the worksheet object). For Document type workbooks, this method has no effect.
|
0.2.2 | - One Billion Cells
- Achievement Unlocked: A simple test using ExcelJS has created a spreadsheet with 1,000,000,000 cells. Made using random data with 100,000,000 rows of 10 cells per row. I cannot validate the file yet as Excel will not open it and I have yet to implement the streaming reader but I have every confidence that it is good since 1,000,000 rows loads ok.
|
0.2.3 | - Bug Fixes
- Streaming XLSX Writer
- At long last ExcelJS can support writing massive XLSX files in a scalable memory efficient manner. Performance has been optimised and even smaller spreadsheets can be faster to write than the document writer. Options have been added to control the use of shared strings and styles as these can both have a considerable effect on performance
- Worksheet.lastRow
- Access the last editable row in a worksheet.
- Row.commit()
- For streaming writers, this method commits the row (and any previous rows) to the stream. Committed rows will no longer be editable (and are typically deleted from the worksheet object). For Document type workbooks, this method has no effect.
|
0.2.4 | |
0.2.6 | - Bug Fixes
- Defined Names
- Cells can now have assigned names which may then be used in formulas.
- Converted Bluebird.defer() to new Bluebird(function(resolve, reject){}). Thanks to user Nishchit for the Pull Request
|
0.2.7 | - Data Validations
- Cells can now define validations that controls the valid values the cell can have
|
0.2.8 | |
0.2.9 | - Fixed "read property 'richText' of undefined error. Thanks to james075
|
0.2.10 | - Refactoring Complete. All unit and integration tests pass.
|
0.2.11 | |
0.2.12 | |
0.2.13 | |
0.2.14 | |
0.2.15 | |
0.2.16 | |
0.2.17 | |
0.2.18 | |
0.2.19 | |
0.2.20 | |
0.2.21 | |
0.2.22 | |
0.2.23 | - Merged Fall back to JSON.stringify() if unknown Cell.Type #137 with some modification. If a cell value is assigned to an unrecognisable javascript object, the stored value in xlsx and csv files will be JSON stringified. Note that if the file is read again, no attempt will be made to parse the stringified JSON text. Thanks to wulfsolter for the contribution.
|
0.2.24 | - Merged Protect cell fix #166. This does not mean full support for protected cells merely that the parser is not confused by the extra xml. Thanks to jayflo for the contribution.
|
0.2.25 | - Added functions to delete cells, rows and columns from a worksheet. Modelled after the Array splice method, the functions allow cells, rows and columns to be deleted (and optionally inserted). See Columns and Rows for details.
Note: Not compatable with cell merges
|
0.2.26 | |
0.2.27 | |
0.2.28 | |
0.2.29 | |
0.2.30 | - Merged Fix issue #178 #201. Adds the following properties to workbook:
- title
- subject
- keywords
- category
- description
- company
- manager
Thanks to stavenko for the contribution.
|
0.2.31 | |
0.2.32 | |
0.2.33 | |
0.2.34 | |
0.2.35 | |
0.2.36 | |
0.2.37 | |
0.2.38 | |
0.2.39 | |
0.2.42 | - Browser Compatable!
- Well mostly. I have added a browser sub-folder that contains a browserified bundle and an index.js that can be used to generate another. See Browser section for details.
- Fixed corrupted theme.xml. Apologies for letting that through.
- Merged [BUGFIX] data validation formulae undefined #253. Thanks to jayflo for the contribution.
|
0.2.43 | |
0.2.44 | - Reduced Dependencies.
- Goodbye lodash, goodbye bluebird. Minified bundle is now just over half what it was in the first version.
|
0.2.45 | |
0.2.46 | |
0.3.0 | |
0.3.1 | |
0.4.0 | |
0.4.1 | |
0.4.2 | Addressed the following issues: These issues are potentially caused by a bug that caused colours with zero themes, tints or indexes to be rendered and parsed incorrectly.Regarding themes: the theme files stored inside the xlsx container hold important information regarding colours, styles etc and if the theme information from a loaded xlsx file is lost, the results can be unpredictable and undesirable. To address this, when an ExcelJS Workbook parses an XLSX file, it will preserve any theme files it finds and include them when writing to a new XLSX. If this behaviour is not desired, the Workbook class exposes a clearThemes() function which will drop the theme content. Note that this behaviour is only implemented in the document based Workbook class, not the streamed Reader and Writer.
|
0.4.3 | |
0.4.4 | |
0.4.6 | |
0.4.9 | - Switching to transpiled code for distribution. This will ensure compatability with 4.0.0 and above from here on. And it will also allow use of much more expressive JS code in the lib folder!
- Basic Image Support!Images can now be added to worksheets either as a tiled background or stretched over a range. Note: other features like rotation, etc. are not supported yet and will reqeuire further work.
|
0.4.10 | |
0.4.11 | |
0.4.12 | |
0.4.13 | |
0.4.14 | |
0.5.0 | |
0.5.1 | |
0.6.0 | |
0.6.1 | |
0.6.2 | |
0.7.0 | |
0.7.1 | |
0.8.0 | |
0.8.1 | |
0.8.2 | |
0.8.3 | |
0.8.4 | |
0.8.5 | |
0.9.0 | |
0.9.1 | |
1.0.0 | |
1.0.1 | |
1.0.2 | |
1.1.0 | |
1.1.1 | |
1.1.2 | |
1.1.3 | |
1.2.0 | |
1.2.1 | |
1.3.0 | |
1.4.2 | |
1.4.3 | |
1.4.5 | |
1.4.6 | |
1.4.7 | |
1.4.8 | |
1.4.9 | |
1.4.10 | |
1.4.12 | |
1.4.13 | |
1.5.0 | |
1.5.1 | |
1.6.0 | |
1.6.1 | |
1.6.2 | |
1.6.3 | |
1.7.0 | |
1.8.0 | |
1.9.0 | |
1.9.1 | |
1.10.0 | |