Gathering detailed insights and metrics for jsreport-exceljs
Gathering detailed insights and metrics for jsreport-exceljs
Gathering detailed insights and metrics for jsreport-exceljs
Gathering detailed insights and metrics for jsreport-exceljs
npm install jsreport-exceljs
Typescript
Module System
Min. Node Version
Node Version
NPM Version
77.6
Supply Chain
86.5
Quality
76
Maintenance
100
Vulnerability
97
License
JavaScript (99.66%)
HTML (0.23%)
TypeScript (0.1%)
Total Downloads
436,440
Last Day
664
Last Week
2,603
Last Month
12,375
Last Year
140,975
14,039 Stars
1,775 Commits
1,795 Forks
180 Watching
14 Branches
187 Contributors
Minified
Minified + Gzipped
Latest Version
4.0.1
Package Id
jsreport-exceljs@4.0.1
Unpacked Size
9.03 MB
Size
1.76 MB
File Count
488
NPM Version
10.8.3
Node Version
18.20.4
Publised On
28 Oct 2024
Cumulative downloads
Total Downloads
Last day
-2.8%
664
Compared to previous day
Last week
-20.9%
2,603
Compared to previous week
Last month
-3.9%
12,375
Compared to previous month
Last year
32.2%
140,975
Compared to previous year
35
Read, manipulate and write spreadsheet data and styles to XLSX and JSON.
Reverse engineered from Excel spreadsheet files as a project.
1npm install exceljs
Contributions are very welcome! It helps me know what features are desired or what bugs are causing the most pain.
I have just one request; If you submit a pull request for a bugfix, please add a unit-test or integration-test (in the spec folder) that catches the problem. Even a PR that just has a failing test is fine - I can analyse what the test is doing and fix the code from that.
Note: Please try to avoid modifying the package version in a PR. Versions are updated on release and any change will most likely result in merge collisions.
To be clear, all contributions added to this library will be included in the library's MIT licence.
1const ExcelJS = require('exceljs');
To use the ES5 transpiled code, use the dist/es5 path.
1const ExcelJS = require('exceljs/dist/es5');
Note: The ES5 build has an implicit dependency on a number of polyfills which are no longer explicitly added by exceljs. You will need to add "core-js" and "regenerator-runtime" to your dependencies and include the following requires in your code before the exceljs import:
1// polyfills required by exceljs 2require('core-js/modules/es.promise'); 3require('core-js/modules/es.object.assign'); 4require('core-js/modules/es.object.keys'); 5require('regenerator-runtime/runtime'); 6 7// ... 8 9const ExcelJS = require('exceljs/dist/es5');
ExcelJS publishes two browserified bundles inside the dist/ folder:
One with implicit dependencies on core-js polyfills...
1<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.js"></script> 2<script src="exceljs.js"></script>
And one without...
1<script src="--your-project's-pollyfills-here--"></script> 2<script src="exceljs.bare.js"></script>
1var workbook = new Excel.Workbook();
1workbook.creator = 'Me'; 2workbook.lastModifiedBy = 'Her'; 3workbook.created = new Date(1985, 8, 30); 4workbook.modified = new Date(); 5workbook.lastPrinted = new Date(2016, 9, 27);
1// Set workbook dates to 1904 date system 2workbook.properties.date1904 = true;
1// Force workbook calculation on load 2workbook.calcProperties.fullCalcOnLoad = true;
The Workbook views controls how many separate windows Excel will open when viewing the workbook.
1workbook.views = [ 2 { 3 x: 0, y: 0, width: 10000, height: 20000, 4 firstSheet: 0, activeTab: 1, visibility: 'visible' 5 } 6]
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:[{state: 'frozen', xSplit: 1, ySplit:1}]});
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)
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);
1// make worksheet visible 2worksheet.state = 'visible'; 3 4// make worksheet hidden 5worksheet.state = 'hidden'; 6 7// make worksheet hidden from 'hide/unhide' dialog 8worksheet.state = 'veryHidden';
Worksheets support a property bucket to allow control over some features of the worksheet.
1// create new sheet with properties 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 |
defaultColWidth | (optional) | Default column width |
dyDescent | 55 | TBD |
Some new metrics have been added to Worksheet...
Name | Description |
---|---|
rowCount | The total row size of the document. Equal to the row number of the last row that has values. |
actualRowCount | A count of the number of rows that have values. If a mid-document row is empty, it will not be included in the count. |
columnCount | The total column size of the document. Equal to the maximum cell count from all of the rows |
actualColumnCount | A count of the number of columns that have values. |
All properties that can affect the printing of a sheet are held in a pageSetup object on the sheet.
1// create new sheet with pageSetup settings for A4 - landscape 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// Set multiple Print Areas by separating print areas with '&&' 22worksheet.pageSetup.printArea = 'A1:G10&&A11:G20'; 23 24// Repeat specific rows on every printed page 25worksheet.pageSetup.printTitlesRow = '1:3'; 26 27// Repeat specific columns on every printed page 28worksheet.pageSetup.printTitlesColumn = 'A:C';
Supported pageSetup settings
Name | Default | Description |
---|---|---|
margins | Whitespace on the borders of the page. Units are inches. | |
orientation | 'portrait' | Orientation of the page - i.e. taller (portrait) or wider (landscape) |
horizontalDpi | 4294967295 | Horizontal Dots per Inch. Default value is -1 |
verticalDpi | 4294967295 | Vertical Dots per Inch. Default value is -1 |
fitToPage | Whether to use fitToWidth and fitToHeight or scale settings. Default is based on presence of these settings in the pageSetup object - if both are present, scale wins (i.e. default will be false) | |
pageOrder | 'downThenOver' | Which order to print the pages - one of ['downThenOver', 'overThenDown'] |
blackAndWhite | false | Print without colour |
draft | false | Print with less quality (and ink) |
cellComments | 'None' | Where to place comments - one of ['atEnd', 'asDisplayed', 'None'] |
errors | 'displayed' | Where to show errors - one of ['dash', 'blank', 'NA', 'displayed'] |
scale | 100 | Percentage value to increase or reduce the size of the print. Active when fitToPage is false |
fitToWidth | 1 | How many pages wide the sheet should print on to. Active when fitToPage is true |
fitToHeight | 1 | How many pages high the sheet should print on to. Active when fitToPage is true |
paperSize | What paper size to use (see below) | |
showRowColHeaders | false | Whether to show the row numbers and column letters |
showGridLines | false | Whether to show grid lines |
firstPageNumber | Which number to use for the first page | |
horizontalCentered | false | Whether to center the sheet data horizontally |
verticalCentered | false | Whether to center the sheet data vertically |
Example Paper Sizes
Name | Value |
---|---|
Letter | undefined |
Legal | 5 |
Executive | 7 |
A4 | 9 |
A5 | 11 |
B5 (JIS) | 13 |
Envelope #10 | 20 |
Envelope DL | 27 |
Envelope C5 | 28 |
Envelope B5 | 34 |
Envelope Monarch | 37 |
Double Japan Postcard Rotated | 82 |
16K 197x273 mm | 119 |
Here's how to add headers and footers. The added content is mainly text, such as time, introduction, file information, etc., and you can set the style of the text. In addition, you can set different texts for the first page and even page.
Note: Images are not currently supported.
1// 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 |
Worksheets now support a list of views, that control how Excel presents the sheet:
Each view also supports various properties:
Name | Default | Description |
---|---|---|
state | 'normal' | Controls the view state - one of normal, frozen or split |
rightToLeft | false | Sets the worksheet view's orientation to right-to-left |
activeCell | undefined | The currently selected cell |
showRuler | true | Shows or hides the ruler in Page Layout |
showRowColHeaders | true | Shows or hides the row and column headers (e.g. A1, B1 at the top and 1,2,3 on the left |
showGridLines | true | Shows or hides the gridlines (shown for cells where borders have not been defined) |
zoomScale | 100 | Percentage zoom to use for the view |
zoomScaleNormal | 100 | Normal zoom for the view |
style | undefined | Presentation style - one of pageBreakPreview or pageLayout. Note pageLayout is not compatable with frozen views |
Frozen views support the following extra properties:
Name | Default | Description |
---|---|---|
xSplit | 0 | How many columns to freeze. To freeze rows only, set this to 0 or undefined |
ySplit | 0 | How many rows to freeze. To freeze columns only, set this to 0 or undefined |
topLeftCell | special | Which cell will be top-left in the bottom-right pane. Note: cannot be a frozen cell. Defaults to first unfrozen cell |
1worksheet.views = [ 2 {state: 'frozen', xSplit: 2, ySplit: 3, topLeftCell: 'G10', activeCell: 'A1'} 3];
Split views support the following extra properties:
Name | Default | Description |
---|---|---|
xSplit | 0 | How many points from the left to place the splitter. To split vertically, set this to 0 or undefined |
ySplit | 0 | How many points from the top to place the splitter. To split horizontally, set this to 0 or undefined |
topLeftCell | undefined | Which cell will be top-left in the bottom-right pane. |
activePane | undefined | Which pane will be active - one of topLeft, topRight, bottomLeft and bottomRight |
1worksheet.views = [ 2 {state: 'split', xSplit: 2000, ySplit: 3000, topLeftCell: 'G10', activeCell: 'A1'} 3];
It is possible to apply an auto filter to your worksheet.
1worksheet.autoFilter = 'A1:C1';
While the range string is the standard form of the autoFilter, the worksheet will also support the following values:
1// Set an auto filter from A1 to C1 2worksheet.autoFilter = { 3 from: 'A1', 4 to: 'C1', 5} 6 7// Set an auto filter from the cell in row 3 and column 1 8// to the cell in row 5 and column 12 9worksheet.autoFilter = { 10 from: { 11 row: 3, 12 column: 1 13 }, 14 to: { 15 row: 5, 16 column: 12 17 } 18} 19 20// Set an auto filter from D3 to the 21// cell in row 7 and column 5 22worksheet.autoFilter = { 23 from: 'D3', 24 to: { 25 row: 7, 26 column: 5 27 } 28}
1// Add column headers and define column keys and widths 2// Note: these column structures are a workbook-building convenience only, 3// apart from the column width, they will not be fully persisted. 4worksheet.columns = [ 5 { header: 'Id', key: 'id', width: 10 }, 6 { header: 'Name', key: 'name', width: 32 }, 7 { header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 } 8]; 9 10// Access an individual columns by key, letter and 1-based column number 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
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;
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
1// merge a range of cells 2worksheet.mergeCells('A4:B5'); 3 4// ... merged cells are linked 5worksheet.getCell('B5').value = 'Hello, World!'; 6expect(worksheet.getCell('B5').value).toBe(worksheet.getCell('A4').value); 7expect(worksheet.getCell('B5').master).toBe(worksheet.getCell('A4')); 8 9// ... merged cells share the same style object 10expect(worksheet.getCell('B5').style).toBe(worksheet.getCell('A4').style); 11worksheet.getCell('B5').style.font = myFonts.arial; 12expect(worksheet.getCell('A4').style.font).toBe(myFonts.arial); 13 14// unmerging the cells breaks the style links 15worksheet.unMergeCells('A4'); 16expect(worksheet.getCell('B5').style).not.toBe(worksheet.getCell('A4').style); 17expect(worksheet.getCell('B5').style.font).not.toBe(myFonts.arial); 18 19// merge by top-left, bottom-right 20worksheet.mergeCells('K10', 'M12'); 21 22// merge by start row, start column, end row, end column (equivalent to K10:M12) 23worksheet.mergeCells(10,11,12,13);
1duplicateRow(start, amount = 1, insert = true) 2 3const wb = new ExcelJS.Workbook(); 4const ws = wb.addWorksheet('duplicateTest'); 5ws.getCell('A1').value = 'One'; 6ws.getCell('A2').value = 'Two'; 7ws.getCell('A3').value = 'Three'; 8ws.getCell('A4').value = 'Four'; 9 10// This line will duplicate the row 'One' twice but it will replace rows 'Two' and 'Three' 11// if third param was true so it would insert 2 new rows with the values and styles of row 'One' 12ws.duplicateRow(1,2,false);
Parameter | Description | Default Value |
---|---|---|
start | Row number you want to duplicate (first in excel is 1) | |
amount | The times you want to duplicate the row | 1 |
insert | true if you want to insert new rows for the duplicates, or false if you want to replace them | true |
Individual cells (or multiple groups of cells) can have names assigned to them. The names can be used in formulas and data validation (and probably more).
1// assign (or get) a name for a cell (will overwrite any other names that cell had) 2worksheet.getCell('A1').name = 'PI'; 3expect(worksheet.getCell('A1').name).to.equal('PI'); 4 5// assign (or get) an array of names for a cell (cells can have more than one name) 6worksheet.getCell('A1').names = ['thing1', 'thing2']; 7expect(worksheet.getCell('A1').names).to.have.members(['thing1', 'thing2']); 8 9// remove a name from a cell 10worksheet.getCell('A1').removeName('thing1'); 11expect(worksheet.getCell('A1').names).to.have.members(['thing2']);
Cells can define what values are valid or not and provide prompting to the user to help guide them.
Validation types can be one of the following:
Type | Description |
---|---|
list | Define a discrete set of valid values. Excel will offer these in a dropdown for easy entry |
whole | The value must be a whole number |
decimal | The value must be a decimal number |
textLength | The value may be text but the length is controlled |
custom | A custom formula controls the valid values |
For types other than list or custom, the following operators affect the validation:
Operator | Description |
---|---|
between | Values must lie between formula results |
notBetween | Values must not lie between formula results |
equal | Value must equal formula result |
notEqual | Value must not equal formula result |
greaterThan | Value must be greater than formula result |
lessThan | Value must be less than formula result |
greaterThanOrEqual | Value must be greater than or equal to formula result |
lessThanOrEqual | Value must be less than or equal to formula result |
1// Specify list of valid values (One, Two, Three, Four). 2// Excel will provide a dropdown with these values. 3worksheet.getCell('A1').dataValidation = { 4 type: 'list', 5 allowBlank: true, 6 formulae: ['"One,Two,Three,Four"'] 7}; 8 9// Specify list of valid values from a range. 10// Excel will provide a dropdown with these values. 11worksheet.getCell('A1').dataValidation = { 12 type: 'list', 13 allowBlank: true, 14 formulae: ['$D$5:$F$5'] 15}; 16 17// Specify Cell must be a whole number that is not 5. 18// Show the user an appropriate error message if they get it wrong 19worksheet.getCell('A1').dataValidation = { 20 type: 'whole', 21 operator: 'notEqual', 22 showErrorMessage: true, 23 formulae: [5], 24 errorStyle: 'error', 25 errorTitle: 'Five', 26 error: 'The value must not be Five' 27}; 28 29// Specify Cell must be a 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};
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};
Tables allow for in-sheet manipulation of tabular data.
To add a table to a worksheet, define a table model and call addTable:
1// add a table to a sheet 2ws.addTable({ 3 name: 'MyTable', 4 ref: 'A1', 5 headerRow: true, 6 totalsRow: true, 7 style: { 8 theme: 'TableStyleDark3', 9 showRowStripes: true, 10 }, 11 columns: [ 12 {name: 'Date', totalsRowLabel: 'Totals:', filterButton: true}, 13 {name: 'Amount', totalsRowFunction: 'sum', filterButton: false}, 14 ], 15 rows: [ 16 [new Date('2019-07-20'), 70.10], 17 [new Date('2019-07-21'), 70.60], 18 [new Date('2019-07-22'), 70.10], 19 ], 20});
Note: Adding a table to a worksheet will modify the sheet by placing headers and row data to the sheet. Any data on the sheet covered by the resulting table (including headers and totals) will be overwritten.
The following table defines the properties supported by tables.
Table Property | Description | Required | Default Value |
---|---|---|---|
name | The name of the table | Y | |
displayName | The display name of the table | N | name |
ref | Top left cell of the table | Y | |
headerRow | Show headers at top of table | N | true |
totalsRow | Show totals at bottom of table | N | false |
style | Extra style properties | N | {} |
columns | Column definitions | Y | |
rows | Rows of data | Y |
The following table defines the properties supported within the table style property.
Style Property | Description | Required | Default Value |
---|---|---|---|
theme | The colour theme of the table | N | 'TableStyleMedium2' |
showFirstColumn | Highlight the first column (bold) | N | false |
showLastColumn | Highlight the last column (bold) | N | false |
showRowStripes | Alternate rows shown with background colour | N | false |
showColumnStripes | Alternate rows shown with background colour | N | false |
The following table defines the properties supported within each table column.
Column Property | Description | Required | Default Value |
---|---|---|---|
name | The name of the column, also used in the header | Y | |
filterButton | Switches the filter control in the header | N | false |
totalsRowLabel | Label to describe the totals row (first column) | N | 'Total' |
totalsRowFunction | Name of the totals function | N | 'none' |
totalsRowFormula | Optional formula for custom functions | N |
The following table list the valid values for the totalsRowFunction property defined by columns. If any value other than 'custom' is used, it is not necessary to include the associated formula as this will be inserted by the table.
Totals Functions | Description |
---|---|
none | No totals function for this column |
average | Compute average for the column |
countNums | Count the entries that are numbers |
count | Count of entries |
max | The maximum value in this column |
min | The minimum value in this column |
stdDev | The standard deviation for this column |
var | The variance for this column |
sum | The sum of entries for this column |
custom | A custom formula. Requires an associated totalsRowFormula value. |
Valid theme names follow the following pattern:
Shades, Numbers can be one of:
For no theme, use the value null.
Note: custom table themes are not supported by exceljs yet.
Tables support a set of manipulation functions that allow data to be added or removed and some properties to be changed. Since many of these operations may have on-sheet effects, the changes must be committed once complete.
All index values in the table are zero based, so the first row number and first column number is 0.
Adding or Removing Headers and Totals
1const table = ws.getTable('MyTable'); 2 3// turn header row on 4table.headerRow = true; 5 6// turn totals row off 7table.totalsRow = false; 8 9// commit the table changes into the sheet 10table.commit();
Relocating a Table
1const table = ws.getTable('MyTable'); 2 3// table top-left move to D4 4table.ref = 'D4'; 5 6// commit the table changes into the sheet 7table.commit();
Adding and Removing Rows
1const table = ws.getTable('MyTable'); 2 3// remove first two rows 4table.removeRows(0, 2); 5 6// insert new rows at index 5 7table.addRow([new Date('2019-08-05'), 5, 'Mid'], 5); 8 9// append new row to bottom of table 10table.addRow([new Date('2019-08-10'), 10, 'End']); 11 12// commit the table changes into the sheet 13table.commit();
Adding and Removing Columns
1const table = ws.getTable('MyTable'); 2 3// remove second column 4table.removeColumnss(1, 1); 5 6// insert new column (with data) at index 1 7table.addColumn( 8 {name: 'Letter', totalsRowFunction: 'custom', totalsRowFormula: 'ROW()', totalsRowResult: 6, filterButton: true}, 9 ['a', 'b', 'c', 'd'], 10 2 11); 12 13// commit the table changes into the sheet 14table.commit();
Change Column Properties
1const table = ws.getTable('MyTable'); 2 3// Get Column Wrapper for second column 4const column = table.getColumn(1); 5 6// set some properties 7column.name = 'Code'; 8column.filterButton = true; 9column.style = {font:{bold: true, name: 'Comic Sans MS'}}; 10column.totalsRowLabel = 'Totals'; 11column.totalsRowFunction = 'custom'; 12column.totalsRowFormula = 'ROW()'; 13column.totalsRowResult = 10; 14 15// commit the table changes into the sheet 16table.commit();
Cells, Rows and Columns each support a rich set of styles and formats that affect how the cells are displayed.
Styles are set by assigning the following properties:
1// assign a style to a cell 2ws.getCell('A1').numFmt = '0.00%'; 3 4// Apply styles to worksheet columns 5ws.columns = [ 6 { header: 'Id', key: 'id', width: 10 }, 7 { header: 'Name', key: 'name', width: 32, style: { font: { name: 'Arial Black' } } }, 8 { header: 'D.O.B.', key: 'DOB', width: 10, style: { numFmt: 'dd/mm/yyyy' } } 9]; 10 11// Set Column 3 to Currency Format 12ws.getColumn(3).numFmt = '"£"#,##0.00;[Red]\-"£"#,##0.00'; 13 14// Set Row 2 to Comic Sans. 15ws.getRow(2).font = { name: 'Comic Sans MS', family: 4, size: 16, underline: 'double', bold: true };
When a style is applied to a row or column, it will be applied to all currently existing cells in that row or column. Also, any new cell that is created will inherit its initial styles from the row and column it belongs to.
If a cell's row and column both define a specific style (e.g. font), the cell will use the row style over the column style. However if the row and column define different styles (e.g. column.numFmt and row.font), the cell will inherit the font from the row and the numFmt from the column.
Caveat: All the above properties (with the exception of numFmt, which is a string), are JS object structures. If the same style object is assigned to more than one spreadsheet entity, then each entity will share the same style object. If the style object is later modified before the spreadsheet is serialized, then all entities referencing that style object will be modified too. This behaviour is intended to prioritize performance by reducing the number of JS objects created. If you want the style objects to be independent, you will need to clone them before assigning them. Also, by default, when a document is read from file (or stream) if spreadsheet entities share similar styles, then they will reference the same style object too.
1// display value as '1 3/5' 2ws.getCell('A1').value = 1.6; 3ws.getCell('A1').numFmt = '# ?/?'; 4 5// display value as '1.60%' 6ws.getCell('B1').value = 0.016; 7ws.getCell('B1').numFmt = '0.00%';
1 2// for the wannabe graphic designers out there 3ws.getCell('A1').font = { 4 name: 'Comic Sans MS', 5 family: 4, 6 size: 16, 7 underline: true, 8 bold: true 9}; 10 11// for the graduate graphic designers... 12ws.getCell('A2').font = { 13 name: 'Arial Black', 14 color: { argb: 'FF00FF00' }, 15 family: 2, 16 size: 14, 17 italic: true 18}; 19 20// for the vertical align 21ws.getCell('A3').font = { 22 vertAlign: 'superscript' 23}; 24 25// note: the cell will store a reference to the font object assigned. 26// If the font object is changed afterwards, the cell font will change also... 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' |
1// set cell alignment to top-left, middle-center, bottom-right 2ws.getCell('A1').alignment = { vertical: 'top', horizontal: 'left' }; 3ws.getCell('B1').alignment = { vertical: 'middle', horizontal: 'center' }; 4ws.getCell('C1').alignment = { vertical: 'bottom', horizontal: 'right' }; 5 6// set cell to wrap-text 7ws.getCell('D1').alignment = { wrapText: true }; 8 9// set cell indent to 1 10ws.getCell('E1').alignment = { indent: 1 }; 11 12// set cell text rotation to 30deg upwards, 45deg downwards and vertical text 13ws.getCell('F1').alignment = { textRotation: 30 }; 14ws.getCell('G1').alignment = { textRotation: -45 }; 15ws.getCell('H1').alignment = { textRotation: 'vertical' };
Valid Alignment Property Values
horizontal | vertical | wrapText | shrinkToFit | indent | readingOrder | textRotation |
---|---|---|---|---|---|---|
left | top | true | true | integer | rtl | 0 to 90 |
center | middle | false | false | ltr | -1 to -90 | |
right | bottom | vertical | ||||
fill | distributed | |||||
justify | justify | |||||
centerContinuous | ||||||
distributed |
1// set single thin border around A1 2ws.getCell('A1').border = { 3 top: {style:'thin'}, 4 left: {style:'thin'}, 5 bottom: {style:'thin'}, 6 right: {style:'thin'} 7}; 8 9// set double thin green border around A3 10ws.getCell('A3').border = { 11 top: {style:'double', color: {argb:'FF00FF00'}}, 12 left: {style:'double', color: {argb:'FF00FF00'}}, 13 bottom: {style:'double', color: {argb:'FF00FF00'}}, 14 right: {style:'double', color: {argb:'FF00FF00'}} 15}; 16 17// set thick red cross in A5 18ws.getCell('A5').border = { 19 diagonal: {up: true, down: true, style:'thick', color: {argb:'FFFF0000'}} 20};
Valid Border Styles
1// fill A1 with red darkVertical stripes 2ws.getCell('A1').fill = { 3 type: 'pattern', 4 pattern:'darkVertical', 5 fgColor:{argb:'FFFF0000'} 6}; 7 8// fill A2 with yellow dark trellis and blue behind 9ws.getCell('A2').fill = { 10 type: 'pattern', 11 pattern:'darkTrellis', 12 fgColor:{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('A4').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};
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
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.
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
Cell level protection can be modified using the protection property.
1ws.getCell('A1').protection = { 2 locked: false, 3 hidden: true, 4};
Supported Protection Properties
Property | Default | Description |
---|---|---|
locked | true | Specifies whether a cell will be locked if the sheet is protected. |
hidden | false | Specifies whether a cell's formula will be visible if the sheet is protected. |
Conditional formatting allows a sheet to show specific styles, icons, etc depending on cell values or any arbitrary formula.
Conditional formatting rules are added at the sheet level and will typically cover a range of cells.
Multiple rules can be applied to a given cell range and each rule will apply its own style.
If multiple rules affect a given cell, the rule priority value will determine which rule wins out if competing styles collide. The rule with the lower priority value wins. If priority values are not specified for a given rule, ExcelJS will assign them in ascending order.
Note: at present, only a subset of conditional formatting rules are supported. Specifically, only the formatting rules that do not require XML rendering inside an <extLst> element. This means that datasets and three specific icon sets (3Triangles, 3Stars, 5Boxes) are not supported.
1// add a checkerboard pattern to A1:E7 based on row + col being even or odd 2worksheet.addConditionalFormatting({ 3 ref: 'A1:E7', 4 rules: [ 5 { 6 type: 'expression', 7 formulae: ['MOD(ROW()+COLUMN(),2)=0'], 8 style: {fill: {type: 'pattern', pattern: 'solid', bgColor: {argb: 'FF00FF00'}}}, 9 } 10 ] 11})
Supported Conditional Formatting Rule Types
Type | Description |
---|---|
expression | Any custom function may be used to activate the rule. |
cellIs | Compares cell value with supplied formula using specified operator |
top10 | Applies formatting to cells with values in top (or bottom) ranges |
aboveAverage | Applies formatting to cells with values above (or below) average |
colorScale | Applies a coloured background to cells based on where their values lie in the range |
iconSet | Adds one of a range of icons to cells based on value |
containsText | Applies formatting based on whether cell a specific text |
timePeriod | Applies formatting based on whether cell datetime value lies within a specified range |
Field | Optional | Default | Description |
---|---|---|---|
type | 'expression' | ||
priority | Y | <auto> | determines priority ordering of styles |
formulae | array of 1 formula string that returns a true/false value. To reference the cell value, use the top-left cell address | ||
style | style structure to apply if the formula returns true |
Field | Optional | Default | Description |
---|---|---|---|
type | 'cellIs' | ||
priority | Y | <auto> | determines priority ordering of styles |
operator | how to compare cell value with formula result | ||
formulae | array of 1 formula string that returns the value to compare against each cell | ||
style | style structure to apply if the comparison returns true |
Cell Is Operators
Operator | Description |
---|---|
equal | Apply format if cell value equals formula value |
greaterThan | Apply format if cell value is greater than formula value |
lessThan | Apply format if cell value is less than formula value |
between | Apply format if cell value is between two formula values (inclusive) |
Field | Optional | Default | Description |
---|---|---|---|
type | 'top10' | ||
priority | Y | <auto> | determines priority ordering of styles |
rank | Y | 10 | specifies how many top (or bottom) values are included in the formatting |
percent | Y | false | if true, the rank field is a percentage, not an absolute |
bottom | Y | false | if true, the bottom values are included instead of the top |
style | style structure to apply if the comparison returns true |
Field | Optional | Default | Description |
---|---|---|---|
type | 'aboveAverage' | ||
priority | Y | <auto> | determines priority ordering of styles |
aboveAverage | Y | false | if true, the rank field is a percentage, not an absolute |
style | style structure to apply if the comparison returns true |
Field | Optional | Default | Description |
---|---|---|---|
type | 'colorScale' | ||
priority | Y | <auto> | determines priority ordering of styles |
cfvo | array of 2 to 5 Conditional Formatting Value Objects specifying way-points in the value range | ||
color | corresponding array of colours to use at given way points | ||
style | style structure to apply if the comparison returns true |
Field | Optional | Default | Description |
---|---|---|---|
type | 'iconSet' | ||
priority | Y | <auto> | determines priority ordering of styles |
iconSet | Y | 3TrafficLights | name of icon set to use |
cfvo | array of 2 to 5 Conditional Formatting Value Objects specifying way-points in the value range | ||
style | style structure to apply if the comparison returns true |
Field | Optional | Default | Description |
---|---|---|---|
type | 'containsText' | ||
priority | Y | <auto> | determines priority ordering of styles |
operator | type of text comparison | ||
text | text to search for | ||
style | style structure to apply if the comparison returns true |
Contains Text Operators
Operator | Description |
---|---|
containsText | Apply format if cell value contains the value specified in the 'text' field |
containsBlanks | Apply format if cell value contains blanks |
notContainsBlanks | Apply format if cell value does not contain blanks |
containsErrors | Apply format if cell value contains errors |
notContainsErrors | Apply format if cell value does not contain errors |
Field | Optional | Default | Description |
---|---|---|---|
type | 'timePeriod' | ||
priority | Y | <auto> | determines priority ordering of styles |
timePeriod | what time period to compare cell value to | ||
style | style structure to apply if the comparison returns true |
Time Periods
Time Period | Description |
---|---|
lastWeek | Apply format if cell value falls within the last week |
thisWeek | Apply format if cell value falls in this week |
nextWeek | Apply format if cell value falls in the next week |
yesterday | Apply format if cell value is equal to yesterday |
today | Apply format if cell value is equal to today |
tomorrow | Apply format if cell value is equal to tomorrow |
last7Days | Apply format if cell value falls within the last 7 days |
lastMonth | Apply format if cell value falls in last month |
thisMonth | Apply format if cell value falls in this month |
nextMonth | Apply format if cell value falls in next month |
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};
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.
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});
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);
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});
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});
You can add an image with hyperlinks to a cell, and defines the hyperlinks in image range.
1worksheet.addImage(imageId2, { 2 tl: { col: 0, row: 0 }, 3 ext: { width: 500, height: 200 }, 4 hyperlinks: { 5 hyperlink: 'http://www.somewhere.com', 6 tooltip: 'http://www.somewhere.com' 7 } 8});
Worksheets can be protected from modification by adding a password.
1await worksheet.protect('the-password', options);
Worksheet protection can also be removed:
1worksheet.unprotect();
See Cell Protection for details on how to modify individual cell protection.
Note: While the protect() function ret
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
Found 22/30 approved changesets -- score normalized to 7
Reason
0 commit(s) and 4 issue activity found in the last 90 days -- score normalized to 3
Reason
dependency not pinned by hash detected -- score normalized to 2
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
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