Gathering detailed insights and metrics for xlsx-populate
Gathering detailed insights and metrics for xlsx-populate
Gathering detailed insights and metrics for xlsx-populate
Gathering detailed insights and metrics for xlsx-populate
xlsx-populate-wrapper
xlsx-populate wrapper library for working with Excel data
@eyeseetea/xlsx-populate
Excel XLSX parser/generator written in JavaScript with Node.js and browser support, jQuery/d3-style method chaining, and a focus on keeping existing workbook features and styles in tact.
jest-serializer-xlsx-populate
Turn an [xlsx-populate](https://github.com/dtjohnson/xlsx-populate) workbook into a pretty snapshot.
xlsx-populate-types
TypeScript definitions for XLSX-Populate
Excel XLSX parser/generator written in JavaScript with Node.js and browser support, jQuery/d3-style method chaining, encryption, and a focus on keeping existing workbook features and styles in tact.
npm install xlsx-populate
Typescript
Module System
Node Version
NPM Version
83.6
Supply Chain
97
Quality
74.9
Maintenance
100
Vulnerability
98.6
License
JavaScript (99.71%)
C# (0.29%)
Total Downloads
11,780,671
Last Day
4,043
Last Week
50,643
Last Month
301,084
Last Year
3,252,981
960 Stars
482 Commits
185 Forks
31 Watching
30 Branches
21 Contributors
Minified
Minified + Gzipped
Latest Version
1.21.0
Package Id
xlsx-populate@1.21.0
Size
3.35 MB
NPM Version
6.13.4
Node Version
12.16.1
Publised On
01 Mar 2020
Cumulative downloads
Total Downloads
Last day
-71.7%
4,043
Compared to previous day
Last week
-33.1%
50,643
Compared to previous week
Last month
-19.2%
301,084
Compared to previous month
Last year
16.2%
3,252,981
Compared to previous year
31
Excel XLSX parser/generator written in JavaScript with Node.js and browser support, jQuery/d3-style method chaining, encryption, and a focus on keeping existing workbook features and styles in tact.
1npm install xlsx-populate
Note that xlsx-populate uses ES6 features so only Node.js v4+ is supported.
A functional browser example can be found in examples/browser/index.html.
xlsx-populate is written first for Node.js. We use browserify and babelify to transpile and pack up the module for use in the browser.
You have a number of options to include the code in the browser. You can download the combined, minified code from the browser directory in this repository or you can install with bower:
1bower install xlsx-populate
After including the module in the browser, it is available globally as XlsxPopulate
.
Alternatively, you can require this module using browserify. Since xlsx-populate uses ES6 features, you will also need to use babelify with babel-preset-env.
xlsx-populate has an extensive API for working with Excel workbooks. This section reviews the most common functions and use cases. Examples can also be found in the examples directory of the source code.
To populate data in a workbook, you first load one (either blank, from data, or from file). Then you can access sheets and cells within the workbook to manipulate them.
1const XlsxPopulate = require('xlsx-populate'); 2 3// Load a new blank workbook 4XlsxPopulate.fromBlankAsync() 5 .then(workbook => { 6 // Modify the workbook. 7 workbook.sheet("Sheet1").cell("A1").value("This is neat!"); 8 9 // Write to file. 10 return workbook.toFileAsync("./out.xlsx"); 11 });
You can pull data out of existing workbooks using Cell.value as a getter without any arguments:
1const XlsxPopulate = require('xlsx-populate'); 2 3// Load an existing workbook 4XlsxPopulate.fromFileAsync("./Book1.xlsx") 5 .then(workbook => { 6 // Modify the workbook. 7 const value = workbook.sheet("Sheet1").cell("A1").value(); 8 9 // Log the value. 10 console.log(value); 11 });
Note: in cells that contain values calculated by formulas, Excel will store the calculated value in the workbook. The value method will return the value of the cells at the time the workbook was saved. xlsx-populate will not recalculate the values as you manipulate the workbook and will not write the values to the output.
xlsx-populate also supports ranges of cells to allow parsing/manipulation of multiple cells at once.
1const r = workbook.sheet(0).range("A1:C3"); 2 3// Set all cell values to the same value: 4r.value(5); 5 6// Set the values using a 2D array: 7r.value([ 8 [1, 2, 3], 9 [4, 5, 6], 10 [7, 8, 9] 11]); 12 13// Set the values using a callback function: 14r.value((cell, ri, ci, range) => Math.random());
A common use case is to simply pull all of the values out all at once. You can easily do that with the Sheet.usedRange method.
1// Get 2D array of all values in the worksheet. 2const values = workbook.sheet("Sheet1").usedRange().value();
Alternatively, you can set the values in a range with only the top-left cell in the range:
1workbook.sheet(0).cell("A1").value([ 2 [1, 2, 3], 3 [4, 5, 6], 4 [7, 8, 9] 5]);
The set range is returned.
You can access rows and columns in order to change size, hide/show, or access cells within:
1// Get the B column, set its width and unhide it (assuming it was hidden). 2sheet.column("B").width(25).hidden(false); 3 4const cell = sheet.row(5).cell(3); // Returns the cell at C5.
xlsx-populate supports a number of options for managing sheets.
You can get a sheet by name or index or get all of the sheets as an array:
1// Get sheet by index 2const sheet1 = workbook.sheet(0); 3 4// Get sheet by name 5const sheet2 = workbook.sheet("Sheet2"); 6 7// Get all sheets as an array 8const sheets = workbook.sheets();
You can add new sheets:
1// Add a new sheet named 'New 1' at the end of the workbook 2const newSheet1 = workbook.addSheet('New 1'); 3 4// Add a new sheet named 'New 2' at index 1 (0-based) 5const newSheet2 = workbook.addSheet('New 2', 1); 6 7// Add a new sheet named 'New 3' before the sheet named 'Sheet1' 8const newSheet3 = workbook.addSheet('New 3', 'Sheet1'); 9 10// Add a new sheet named 'New 4' before the sheet named 'Sheet1' using a Sheet reference. 11const sheet = workbook.sheet('Sheet1'); 12const newSheet4 = workbook.addSheet('New 4', sheet);
Note: the sheet rename method does not rename references to the sheet so formulas, etc. can be broken. Use with caution!
You can rename sheets:
1// Rename the first sheet. 2const sheet = workbook.sheet(0).name("new sheet name");
You can move sheets:
1// Move 'Sheet1' to the end 2workbook.moveSheet("Sheet1"); 3 4// Move 'Sheet1' to index 2 5workbook.moveSheet("Sheet1", 2); 6 7// Move 'Sheet1' before 'Sheet2' 8workbook.moveSheet("Sheet1", "Sheet2");
The above methods can all use sheet references instead of names as well. And you can also move a sheet using a method on the sheet:
1// Move the sheet before 'Sheet2' 2sheet.move("Sheet2");
You can delete sheets:
1// Delete 'Sheet1' 2workbook.deleteSheet("Sheet1"); 3 4// Delete sheet with index 2 5workbook.deleteSheet(2); 6 7// Delete from sheet reference 8workbook.sheet(0).delete();
You can get/set the active sheet:
1// Get the active sheet 2const sheet = workbook.activeSheet(); 3 4// Check if the current sheet is active 5sheet.active() // returns true or false 6 7// Activate the sheet 8sheet.active(true); 9 10// Or from the workbook 11workbook.activeSheet("Sheet2");
Excel supports creating defined names that refer to addresses, formulas, or constants. These defined names can be scoped to the entire workbook or just individual sheets. xlsx-populate supports looking up defined names that refer to cells or ranges. (Dereferencing other names will result in an error.) Defined names are particularly useful if you are populating data into a known template. Then you do not need to know the exact location.
1// Look up workbook-scoped name and set the value to 5. 2workbook.definedName("some name").value(5); 3 4// Look of a name scoped to the first sheet and set the value to "foo". 5workbook.sheet(0).definedName("some other name").value("foo");
You can also create, modify, or delete defined names:
1// Create/modify a workbook-scope defined name 2workbook.definedName("some name", "TRUE"); 3 4// Delete a sheet-scoped defined name: 5workbook.sheet(0).definedName("some name", null);
You can search for occurrences of text in cells within the workbook or sheets and optionally replace them.
1// Find all occurrences of the text "foo" in the workbook and replace with "bar". 2workbook.find("foo", "bar"); // Returns array of matched cells 3 4// Find the matches but don't replace. 5workbook.find("foo"); 6 7// Just look in the first sheet. 8workbook.sheet(0).find("foo"); 9 10// Check if a particular cell matches the value. 11workbook.sheet("Sheet1").cell("A1").find("foo"); // Returns true or false
Like String.replace, the find method can also take a RegExp search pattern and replace can take a function callback:
1// Use a RegExp to replace all lowercase letters with uppercase
2workbook.find(/[a-z]+/g, match => match.toUpperCase());
xlsx-populate supports a wide range of cell formatting. See the Style Reference for the various options.
To get/set a cell style:
1// Get a single style 2const bold = cell.style("bold"); // true 3 4// Get multiple styles 5const styles = cell.style(["bold", "italic"]); // { bold: true, italic: true } 6 7// Set a single style 8cell.style("bold", true); 9 10// Set multiple styles 11cell.style({ bold: true, italic: true });
Similarly for ranges:
1// Set all cells in range with a single style 2range.style("bold", true); 3 4// Set with a 2D array 5range.style("bold", [[true, false], [false, true]]); 6 7// Set with a callback function 8range.style("bold", (cell, ri, ci, range) => Math.random() > 0.5); 9 10// Set multiple styles using any combination 11range.style({ 12 bold: true, 13 italic: [[true, false], [false, true]], 14 underline: (cell, ri, ci, range) => Math.random() > 0.5 15});
If you are setting styles for many cells, performance is far better if you set for an entire row or column:
1// Set a single style 2sheet.row(1).style("bold", true); 3 4// Set multiple styles 5sheet.column("A").style({ bold: true, italic: true }); 6 7// Get a single style 8const bold = sheet.column(3).style("bold"); 9 10// Get multiple styles 11const styles = sheet.row(5).style(["bold", "italic"]);
Note that the row/column style behavior mirrors Excel. Setting a style on a column will apply that style to all existing cells and any new cells that are populated. Getting the row/column style will return only the styles that have been applied to the entire row/column, not the styles of every cell in the row or column.
Some styles take values that are more complex objects:
1cell.style("fill", { 2 type: "pattern", 3 pattern: "darkDown", 4 foreground: { 5 rgb: "ff0000" 6 }, 7 background: { 8 theme: 3, 9 tint: 0.4 10 } 11});
There are often shortcuts for the setters, but the getters will always return the full objects:
1cell.style("fill", "0000ff"); 2 3const fill = cell.style("fill"); 4/* 5fill is now set to: 6{ 7 type: "solid", 8 color: { 9 rgb: "0000ff" 10 } 11} 12*/
Number formats are one of the most common styles. They can be set using the numberFormat
style.
1cell.style("numberFormat", "0.00");
Information on how number format codes work can be found here. You can also look up the desired format code in Excel:
You can read/write rich texts to cells.
bold
, italic
, underline
, strikethrough
, subscript
, fontSize
,
fontFamily
, fontGenericFamily
, fontScheme
, fontColor
.
See the Style Reference for the various options.
You can read and modify rich texts on an existing rich text cell:
1// assume A1 is a rich text cell 2const RichText = require('xlsx-Populate').RichText; 3const cell = workbook.sheet(0).cell('A1'); 4cell.value() instanceof RichText // returns true 5const richtext = cell.value(); 6// get the concatenate text 7richtext.text(); 8 9// loop through each rich text fragment 10for (let i = 0; i < richtext.length; i++) { 11 const fragment = richtext.get(i); 12 // Get the style 13 fragment.style('bold'); 14 // Get many styles 15 fragment.style(['bold', 'italic']); 16 // Set one style 17 fragment.style('bold', true); 18 // Set many styles 19 fragment.style({ 'bold': true, 'italic': true }); 20 // Get the value 21 fragment.value(); 22 // Set the value 23 fragment.value('hello'); 24} 25 26// remove the first rich text fragment 27richtext.remove(0); 28 29// clear this rich texts 30richtext.clear();
How to set a cell to rich texts:
1const RichText = require('xlsx-Populate').RichText; 2const cell = workbook.sheet(0).cell('A1'); 3// set a cell value to rich text 4cell.value(new RichText()); 5 6// add two rich text fragments 7cell.value() 8 .add('hello ', { italic: true, bold: true }) 9 .add('world!', { fontColor: 'FF0000' });
You can specify the index when adding rich text fragment.
1// add before the first fragment 2cell.value().add('text', { bold: true }, 0); 3// add before the second fragment 4cell.value().add('text', { bold: true }, 1); 5// add after the last fragment 6cell.value().add('text', { bold: true });
We make a deep copy of the richtext instance when assign it to a cell, which
means you can only modify the content of the richtext before calling cell.value(richtext)
.
Any modification to the richtext instance after calling cell.value(richtext)
will not
save to the cell. i.e.
1const richtext = new RichText(); 2richtext.add('hello'); 3cell.value(richtext); 4cell.value().text(); // returns 'hello' 5 6richtext.add(' world') 7richtext.text(); // returns 'hello world' 8cell.value().text(); // returns 'hello' 9cell.value() === richtext; // returns false 10 11cell.value().add(' world'); 12cell.value().text(); // returns 'hello world'
This means you can create a rich text instance and assign it to any cells! Each cell does not share the same instance but creates a deep copy of the instance.
1const sheet = workbook.sheet(0); 2const richtext = new RichText(); 3richtext.add('hello'); 4const range = sheet.range("A1:C3"); 5range.value(richtext); 6// they do not share the same instance 7sheet.cell('A1').value() === sheet.cell('C1').value() // returns false
You can get the rich text from a cell and set it to anoher cell.
1const richtext = cell1.value(); 2cell2.value(richtext); 3cell1.value() === cell2.value() // returns false
Whenever you call richtext.add(text, styles, index)
, we will detect if the given text
contains line separators (\n
, \r
, \r\n
), if it does, we will call
cell.style('wrapText', true)
for you. MS Excel needs wrapText to be true
to have the new lines displayed, otherwise you will see the texts in one line.
You may also need to set row height to have all lines displayed.
1cell.value() 2 // it support all line separators 3 .add('123\n456\r789\r\n10', { italic: true, fontColor: '123456' }) 4// remember to set height to show the whole row 5workbook.sheet(0).row(1).height(100);
Excel stores date/times as the number of days since 1/1/1900 (sort of). It just applies a number formatting to make the number appear as a date. So to set a date value, you will need to also set a number format for a date if one doesn't already exist in the cell:
1cell.value(new Date(2017, 1, 22)).style("numberFormat", "dddd, mmmm dd, yyyy");
When fetching the value of the cell, it will be returned as a number. To convert it to a date use XlsxPopulate.numberToDate:
1const num = cell.value(); // 42788 2const date = XlsxPopulate.numberToDate(num); // Wed Feb 22 2017 00:00:00 GMT-0500 (Eastern Standard Time)
Data validation is also supported. To set/get/remove a cell data validation:
1// Set the data validation
2cell.dataValidation({
3 type: 'list',
4 allowBlank: false,
5 showInputMessage: false,
6 prompt: false,
7 promptTitle: 'String',
8 showErrorMessage: false,
9 error: 'String',
10 errorTitle: 'String',
11 operator: 'String',
12 formula1: '$A:$A',//Required
13 formula2: 'String'
14});
15
16//Here is a short version of the one above.
17cell.dataValidation('$A:$A');
18
19// Get the data validation
20const obj = cell.dataValidation(); // Returns an object
21
22// Remove the data validation
23cell.dataValidation(null); //Returns the cell
Similarly for ranges:
1
2// Set all cells in range with a single shared data validation
3range.dataValidation({
4 type: 'list',
5 allowBlank: false,
6 showInputMessage: false,
7 prompt: false,
8 promptTitle: 'String',
9 showErrorMessage: false,
10 error: 'String',
11 errorTitle: 'String',
12 operator: 'String',
13 formula1: 'Item1,Item2,Item3,Item4',//Required
14 formula2: 'String'
15});
16
17//Here is a short version of the one above.
18range.dataValidation('Item1,Item2,Item3,Item4');
19
20// Get the data validation
21const obj = range.dataValidation(); // Returns an object
22
23// Remove the data validation
24range.dataValidation(null); //Returns the Range
Please note, the data validation gets applied to the entire range, not each Cell in the range.
xlsx-populate uses method-chaining similar to that found in jQuery and d3. This lets you construct large chains of setters as desired:
1workbook 2 .sheet(0) 3 .cell("A1") 4 .value("foo") 5 .style("bold", true) 6 .relativeCell(1, 0) 7 .formula("A1") 8 .style("italic", true) 9.workbook() 10 .sheet(1) 11 .range("A1:B3") 12 .value(5) 13 .cell(0, 0) 14 .style("underline", "double"); 15
Hyperlinks are also supported on cells using the Cell.hyperlink method. The method will not style the content to look like a hyperlink. You must do that yourself:
1// Set a hyperlink 2cell.value("Link Text") 3 .style({ fontColor: "0563c1", underline: true }) 4 .hyperlink("http://example.com"); 5 6// Set a hyperlink with tooltip 7cell.value("Link Text") 8 .style({ fontColor: "0563c1", underline: true }) 9 .hyperlink({ hyperlink: "http://example.com", tooltip: "example.com" }); 10 11// Get the hyperlink 12const value = cell.hyperlink(); // Returns 'http://example.com' 13 14// Set a hyperlink to email 15cell.value("Click to Email Jeff Bezos") 16 .hyperlink({ email: "jeff@amazon.com", emailSubject: "I know you're a busy man Jeff, but..." }); 17 18// Set a hyperlink to an internal cell using an address string. 19cell.value("Click to go to an internal cell") 20 .hyperlink("Sheet2!A1"); 21 22// Set a hyperlink to an internal cell using a cell object. 23cell.value("Click to go to an internal cell") 24 .hyperlink(workbook.sheet(0).cell("A1"));
Print options are accessed using the Sheet.printOptions method. Defaults are all assumed to be false, so if the attribute is missing, then the method returns false. A method Sheet.printGridLines is provided to offer the convenience of setting both gridLines and gridLinesSet.
1// Print row and column headings
2sheet.printOptions('headings', true);
3
4// Get the headings flag
5const headings = sheet.printOptions('headings'); // Returns true
6
7// Clear flag for center on page vertically when printing
8sheet.printOptions('verticalCentered', undefined);
9
10// Get the verticalCentered flag
11const verticalCentered = sheet.printOptions('verticalCentered'); // Returns false
12
13// Enable grid lines in print
14sheet.printGridLines(true);
15
16// Now both gridLines and gridLinesSet print options are set
17sheet.printOptions('gridLines') === sheet.printOptions('gridLinesSet') === true; // Returns true
18
19// To disable, just disable one of gridLines or gridLinesSet
20sheet.printOptions('gridLineSets', false);
21
22const isPrintGridLinesEnabled = sheet.printGridLines(); // Returns false
Excel requires that all page margins are defined or none at all. To ensure this, please choose an existing or custom preset. See Sheet.pageMarginsPreset.
1// Get the current preset 2sheet.pageMarginsPreset(); // Returns undefined 3 4// Switch to an existing preset 5sheet.pageMarginsPreset('normal');
Page margins are accessed using the Sheet.pageMargins method. If a page margin is not set, the preset will fill in the gaps.
1// Get top margin in inches, note that the current preset is currently set to normal (see above) 2sheet.pageMargins('top'); // Returns 0.75 3 4// Set top page margin in inches 5sheet.pageMargins('top', 1.1); 6 7// Get top page margin in inches. 8const topPageMarginInInches = sheet.pageMargins('top'); // Returns 1.1
SheetView Panes are accessed using the Sheet.panes method. For convenience, we have Sheet.freezePanes, Sheet.splitPanes, Sheet.resetPanes, and type PaneOptions.
1// access Pane options 2sheet.panes(); // return PaneOptions Object 3 4// manually Set Pane options, WARNING: setting wrong options may result in excel fails to open. 5const paneOptions = { state: 'frozen', topLeftCell: 'B2', xSplit: 1, ySplit: 1, activePane: 'bottomRight' } 6sheet.panes(paneOptions); // return PaneOptions Object 7 8// freeze panes (freeze first column and first two rows) 9sheet.freezePanes(1, 2); 10// OR 11sheet.freezePanes('B3'); 12 13// split panes (Horizontal Split Position: 1000 / 20 pt, Vertical Split Position: 2000 / 20 pt) 14sheet.splitPanes(1000, 2000); 15 16// reset to normal panes (no freeze panes and split panes) 17sheet.resetPanes();
You can serve the workbook from express or other web servers with something like this:
1router.get("/download", function (req, res, next) { 2 // Open the workbook. 3 XlsxPopulate.fromFileAsync("input.xlsx") 4 .then(workbook => { 5 // Make edits. 6 workbook.sheet(0).cell("A1").value("foo"); 7 8 // Get the output 9 return workbook.outputAsync(); 10 }) 11 .then(data => { 12 // Set the output file name. 13 res.attachment("output.xlsx"); 14 15 // Send the workbook. 16 res.send(data); 17 }) 18 .catch(next); 19});
Usage in the browser is almost the same. A functional example can be found in examples/browser/index.html. The library is exposed globally as XlsxPopulate
. Existing workbooks can be loaded from a file:
1// Assuming there is a file input in the page with the id 'file-input' 2var file = document.getElementById("file-input").files[0]; 3 4// A File object is a special kind of blob. 5XlsxPopulate.fromDataAsync(file) 6 .then(function (workbook) { 7 // ... 8 });
You can also load from AJAX if you set the responseType to 'arraybuffer':
1var req = new XMLHttpRequest(); 2req.open("GET", "http://...", true); 3req.responseType = "arraybuffer"; 4req.onreadystatechange = function () { 5 if (req.readyState === 4 && req.status === 200){ 6 XlsxPopulate.fromDataAsync(req.response) 7 .then(function (workbook) { 8 // ... 9 }); 10 } 11}; 12 13req.send();
To download the workbook, you can either export as a blob (default behavior) or as a base64 string. You can then insert a link into the DOM and click it:
1workbook.outputAsync() 2 .then(function (blob) { 3 if (window.navigator && window.navigator.msSaveOrOpenBlob) { 4 // If IE, you must uses a different method. 5 window.navigator.msSaveOrOpenBlob(blob, "out.xlsx"); 6 } else { 7 var url = window.URL.createObjectURL(blob); 8 var a = document.createElement("a"); 9 document.body.appendChild(a); 10 a.href = url; 11 a.download = "out.xlsx"; 12 a.click(); 13 window.URL.revokeObjectURL(url); 14 document.body.removeChild(a); 15 } 16 });
Alternatively, you can download via a data URI, but this is not supported by IE:
1workbook.outputAsync("base64") 2 .then(function (base64) { 3 location.href = "data:" + XlsxPopulate.MIME_TYPE + ";base64," + base64; 4 });
xlsx-populate uses promises to manage async input/output. By default it uses the Promise
defined in the browser or Node.js. In browsers that don't support promises (IE) a polyfill is used via JSZip.
1// Get the current promise library in use. 2// Helpful for getting a usable Promise library in IE. 3var Promise = XlsxPopulate.Promise;
If you prefer, you can override the default Promise
library used with another ES6 compliant library like bluebird.
1const Promise = require("bluebird"); 2const XlsxPopulate = require("xlsx-populate"); 3XlsxPopulate.Promise = Promise;
XLSX Agile encryption and descryption are supported so you can read and write password-protected workbooks. To read a protected workbook, pass the password in as an option:
1XlsxPopulate.fromFileAsync("./Book1.xlsx", { password: "S3cret!" })
2 .then(workbook => {
3 // ...
4 });
Similarly, to write a password encrypted workbook:
1workbook.toFileAsync("./out.xlsx", { password: "S3cret!" });
The password option is supported in all output methods. N.B. Workbooks will only be encrypted if you supply a password when outputting even if they had a password when reading.
Encryption support is also available in the browser, but take care! Any password you put in browser code can be read by anyone with access to your code. You should only use passwords that are supplied by the end-user. Also, the performance of encryption/decryption in the browser is far worse than with Node.js. IE, in particular, is extremely slow. xlsx-populate is bundled for browsers with and without encryption support as the encryption libraries increase the size of the bundle a lot.
There are many, many features of the XLSX format that are not yet supported. If your use case needs something that isn't supported please open an issue to show your support. Better still, feel free to contribute a pull request!
If you happen to run into a bug or an issue, please feel free to submit an issue. I only ask that you please include sample JavaScript code that demonstrates the issue. If the problem lies with modifying some template, it is incredibly difficult to debug the issue without the template. So please attach the template if possible. If you have confidentiality concerns, please attach a different workbook that exhibits the issue or you can send your workbook directly to dtjohnson after creating the issue.
Pull requests are very much welcome! If you'd like to contribute, please make sure to read this section carefully first.
An XLSX workbook is essentially a zip of a bunch of XML files. xlsx-populate uses JSZip to unzip the workbook and sax-js to parse the XML documents into corresponding objects. As you call methods, xlsx-populate manipulates the content of those objects. When you generate the output, xlsx-populate uses xmlbuilder-js to convert the objects back to XML and then uses JSZip to rezip them back into a workbook.
The way in which xlsx-populate manipulates objects that are essentially the XML data is very different from the usual way parser/generator libraries work. Most other libraries will deserialize the XML into a rich object model. That model is then manipulated and serialized back into XML upon generation. The challenge with this approach is that the Office Open XML spec is HUGE. It is extremely difficult for libraries to be able to support the entire specification. So these other libraries will deserialize only the portion of the spec they support and any other content/styles in the workbook they don't support are lost. Since xlsx-populate just manipulates the XML data, it is able to preserve styles and other content while still only supporting a fraction of the spec.
You'll need to make sure Node.js v4+ is installed (as xlsx-populate uses ES6 syntax). You'll also need to install gulp:
1npm install -g gulp
Make sure you have git installed. Then follow this guide to see how to check out code, branch, and then submit your code as a pull request. When you check out the code, you'll first need to install the npm dependencies. From the project root, run:
1npm install
The default gulp task is set up to watch the source files for updates and retest while you edit. From the project root just run:
1gulp
You should see the test output in your console window. As you edit files the tests will run again and show you if you've broken anything. (Note that if you've added new files you'll need to restart gulp for the new files to be watched.)
Now write your code and make sure to add Jasmine unit tests. When you are finished, you need to build the code for the browser. Do that by running the gulp build command:
1gulp build
Verify all is working, check in your code, and submit a pull request.
To make sure your code is consistent and high quality, please make sure to follow this checklist before submitting a pull request:
arguments.length
or use ArgHandler
to distinguish.@private
for private methods and @ignore
for any public methods that are internal to xlsx-populate and should not be included in the public API docs.gulp lint
to see them.xlsx-populate uses gulp as a build tool. There are a number of tasks:
Style Name | Type | Description |
---|---|---|
bold | boolean | true for bold, false for not bold |
italic | boolean | true for italic, false for not italic |
underline | boolean|string | true for single underline, false for no underline, 'double' for double-underline |
strikethrough | boolean | true for strikethrough false for not strikethrough |
subscript | boolean | true for subscript, false for not subscript (cannot be combined with superscript) |
superscript | boolean | true for superscript, false for not superscript (cannot be combined with subscript) |
fontSize | number | Font size in points. Must be greater than 0. |
fontFamily | string | Name of font family. |
fontGenericFamily | number | 1: Serif, 2: Sans Serif, 3: Monospace, |
fontScheme | string | 'minor' |'major' |'none' |
fontColor | Color|string|number | Color of the font. If string, will set an RGB color. If number, will set a theme color. |
horizontalAlignment | string | Horizontal alignment. Allowed values: 'left' , 'center' , 'right' , 'fill' , 'justify' , 'centerContinuous' , 'distributed' |
justifyLastLine | boolean | a.k.a Justified Distributed. Only applies when horizontalAlignment === 'distributed' . A boolean value indicating if the cells justified or distributed alignment should be used on the last line of text. (This is typical for East Asian alignments but not typical in other contexts.) |
indent | number | Number of indents. Must be greater than or equal to 0. |
verticalAlignment | string | Vertical alignment. Allowed values: 'top' , 'center' , 'bottom' , 'justify' , 'distributed' |
wrapText | boolean | true to wrap the text in the cell, false to not wrap. |
shrinkToFit | boolean | true to shrink the text in the cell to fit, false to not shrink. |
textDirection | string | Direction of the text. Allowed values: 'left-to-right' , 'right-to-left' |
textRotation | number | Counter-clockwise angle of rotation in degrees. Must be [-90, 90] where negative numbers indicate clockwise rotation. |
angleTextCounterclockwise | boolean | Shortcut for textRotation of 45 degrees. |
angleTextClockwise | boolean | Shortcut for textRotation of -45 degrees. |
rotateTextUp | boolean | Shortcut for textRotation of 90 degrees. |
rotateTextDown | boolean | Shortcut for textRotation of -90 degrees. |
verticalText | boolean | Special rotation that shows text vertical but individual letters are oriented normally. true to rotate, false to not rotate. |
fill | SolidFill|PatternFill|GradientFill|Color|string|number | The cell fill. If Color, will set a solid fill with the color. If string, will set a solid RGB fill. If number, will set a solid theme color fill. |
border | Borders|Border|string|boolean | The border settings. If string, will set outside borders to given border style. If true, will set outside border style to 'thin' . |
borderColor | Color|string|number | Color of the borders. If string, will set an RGB color. If number, will set a theme color. |
borderStyle | string | Style of the outside borders. Allowed values: 'hair' , 'dotted' , 'dashDotDot' , 'dashed' , 'mediumDashDotDot' , 'thin' , 'slantDashDot' , 'mediumDashDot' , 'mediumDashed' , 'medium' , 'thick' , 'double' |
leftBorder, rightBorder, topBorder, bottomBorder, diagonalBorder | Border|string|boolean | The border settings for the given side. If string, will set border to the given border style. If true, will set border style to 'thin' . |
leftBorderColor, rightBorderColor, topBorderColor, bottomBorderColor, diagonalBorderColor | Color|string|number | Color of the given border. If string, will set an RGB color. If number, will set a theme color. |
leftBorderStyle, rightBorderStyle, topBorderStyle, bottomBorderStyle, diagonalBorderStyle | string | Style of the given side. |
diagonalBorderDirection | string | Direction of the diagonal border(s) from left to right. Allowed values: 'up' , 'down' , 'both' |
numberFormat | string | Number format code. See docs here. |
An object representing a color.
Property | Type | Description |
---|---|---|
[rgb] | string | RGB color code (e.g. 'ff0000' ). Either rgb or theme is required. |
[theme] | number | Index of a theme color. Either rgb or theme is required. |
[tint] | number | Optional tint value of the color from -1 to 1. Particularly useful for theme colors. 0.0 means no tint, -1.0 means 100% darken, and 1.0 means 100% lighten. |
An object representing all of the borders.
Property | Type | Description |
---|---|---|
[left] | Border|string|boolean | The border settings for the left side. If string, will set border to the given border style. If true, will set border style to 'thin' . |
[right] | Border|string|boolean | The border settings for the right side. If string, will set border to the given border style. If true, will set border style to 'thin' . |
[top] | Border|string|boolean | The border settings for the top side. If string, will set border to the given border style. If true, will set border style to 'thin' . |
[bottom] | Border|string|boolean | The border settings for the bottom side. If string, will set border to the given border style. If true, will set border style to 'thin' . |
[diagonal] | Border|string|boolean | The border settings for the diagonal side. If string, will set border to the given border style. If true, will set border style to 'thin' . |
An object representing an individual border.
Property | Type | Description |
---|---|---|
style | string | Style of the given border. |
color | Color|string|number | Color of the given border. If string, will set an RGB color. If number, will set a theme color. |
[direction] | string | For diagonal border, the direction of the border(s) from left to right. Allowed values: 'up' , 'down' , 'both' |
An object representing a solid fill.
Property | Type | Description |
---|---|---|
type | 'solid' | |
color | Color|string|number | Color of the fill. If string, will set an RGB color. If number, will set a theme color. |
An object representing a pattern fill.
Property | Type | Description |
---|---|---|
type | 'pattern' | |
pattern | string | Name of the pattern. Allowed values: 'gray125' , 'darkGray' , 'mediumGray' , 'lightGray' , 'gray0625' , 'darkHorizontal' , 'darkVertical' , 'darkDown' , 'darkUp' , 'darkGrid' , 'darkTrellis' , 'lightHorizontal' , 'lightVertical' , 'lightDown' , 'lightUp' , 'lightGrid' , 'lightTrellis' . |
foreground | Color|string|number | Color of the foreground. If string, will set an RGB color. If number, will set a theme color. |
background | Color|string|number | Color of the background. If string, will set an RGB color. If number, will set a theme color. |
An object representing a gradient fill.
Property | Type | Description |
---|---|---|
type | 'gradient' | |
[gradientType] | string | Type of gradient. Allowed values: 'linear' (default), 'path' . With a path gradient, a path is drawn between the top, left, right, and bottom values and a graident is draw from that path to the outside of the cell. |
stops | Array.<{}> | |
stops[].position | number | The position of the stop from 0 to 1. |
stops[].color | Color|string|number | Color of the stop. If string, will set an RGB color. If number, will set a theme color. |
[angle] | number | If linear gradient, the angle of clockwise rotation of the gradient. |
[left] | number | If path gradient, the left position of the path as a percentage from 0 to 1. |
[right] | number | If path gradient, the right position of the path as a percentage from 0 to 1. |
[top] | number | If path gradient, the top position of the path as a percentage from 0 to 1. |
[bottom] | number | If path gradient, the bottom position of the path as a percentage from 0 to 1. |
A cell
A column.
A formula error (e.g. #DIV/0!).
PageBreaks
A range of cells.
A RichText class that contains many RichTextFragment.
A Rich text fragment.
A row.
A worksheet.
A workbook.
object
OOXML uses the CFB file format with Agile Encryption. The details of the encryption are here: https://msdn.microsoft.com/en-us/library/dd950165(v=office.12).aspx
Helpful guidance also take from this Github project: https://github.com/nolze/ms-offcrypto-tool
Object
A cell
Kind: global class
boolean
Cell
string
Column
Cell
string
number
boolean
string
Cell
string
| undefined
Cell
Cell
object
| undefined
Cell
Cell
*
Range
Cell
Row
number
Sheet
*
object.<string, *>
Cell
Range
Cell
Cell
string
| boolean
| number
| Date
| RichText
| undefined
Cell
Range
Workbook
Cell
undefined
*
boolean
Gets a value indicating whether the cell is the active cell in the sheet.
Kind: instance method of Cell
Returns: boolean
- True if active, false otherwise.
Cell
Make the cell the active cell in the sheet.
Kind: instance method of Cell
Returns: Cell
- The cell.
Param | Type | Description |
---|---|---|
active | boolean | Must be set to true . Deactivating directly is not supported. To deactivate, you should activate a different cell instead. |
string
Get the address of the column.
Kind: instance method of Cell
Returns: string
- The address
Param | Type | Description |
---|---|---|
[opts] | Object | Options |
[opts.includeSheetName] | boolean | Include the sheet name in the address. |
[opts.rowAnchored] | boolean | Anchor the row. |
[opts.columnAnchored] | boolean | Anchor the column. |
[opts.anchored] | boolean | Anchor both the row and the column. |
Column
Gets the parent column of the cell.
Kind: instance method of Cell
Returns: Column
- The parent column.
Cell
Clears the contents from the cell.
Kind: instance method of Cell
Returns: Cell
- The cell.
string
Gets the column name of the cell.
Kind: instance method of Cell
Returns: string
- The column name.
number
Gets the column number of the cell (1-based).
Kind: instance method of Cell
Returns: number
- The column number.
boolean
Find the given pattern in the cell and optionally replace it.
Kind: instance method of Cell
Returns: boolean
- A flag indicating if the pattern was found.
Param | Type | Description |
---|---|---|
pattern | string | RegExp | The pattern to look for. Providing a string will result in a case-insensitive substring search. Use a RegExp for more sophisticated searches. |
[replacement] | string | function | The text to replace or a String.replace callback function. If pattern is a string, all occurrences of the pattern in the cell will be replaced. |
string
Gets the formula in the cell. Note that if a formula was set as part of a range, the getter will return 'SHARED'. This is a limitation that may be addressed in a future release.
Kind: instance method of Cell
Returns: string
- The formula in the cell.
Cell
Sets the formula in the cell.
Kind: instance method of Cell
Returns: Cell
- The cell.
Param | Type | Description |
---|---|---|
formula | string | The formula to set. |
string
| undefined
Gets the hyperlink attached to the cell.
Kind: instance method of Cell
Returns: string
| undefined
- The hyperlink or undefined if not set.
Cell
Set or clear the hyperlink on the cell.
Kind: instance method of Cell
Returns: Cell
- The cell.
Param | Type | Description |
---|---|---|
hyperlink | string | Cell | undefined | The hyperlink to set or undefined to clear. |
Cell
Set the hyperlink options on the cell.
Kind: instance method of Cell
Returns: Cell
- The cell.
Param | Type | Description |
---|---|---|
opts | Object | Cell | Options or Cell. If opts is a Cell then an internal hyperlink is added. |
[opts.hyperlink] | string | Cell | The hyperlink to set, can be a Cell or an internal/external string. |
[opts.tooltip] | string | Additional text to help the user understand more about the hyperlink. |
[opts.email] | string | Email address, ignored if opts.hyperlink is set. |
[opts.emailSubject] | string | Email subject, ignored if opts.hyperlink is set. |
object
| undefined
Gets the data validation object attached to the cell.
Kind: instance method of Cell
Returns: object
| undefined
- The data validation or undefined if not set.
Cell
Set or clear the data validation object of the cell.
Kind: instance method of Cell
Returns: Cell
- The cell.
Param | Type | Description |
---|---|---|
dataValidation | object | undefined | Object or null to clear. |
Cell
Invoke a callback on the cell and return the cell. Useful for method chaining.
Kind: instance method of Cell
Returns: Cell
- The cell.
Param | Type | Description |
---|---|---|
callback | tapCallback | The callback function. |
*
Invoke a callback on the cell and return the value provided by the callback. Useful for method chaining.
Kind: instance method of Cell
Returns: *
- The return value of the callback.
Param | Type | Description |
---|---|---|
callback | thruCallback | The callback function. |
Range
Create a range from this cell and another.
Kind: instance method of Cell
Returns: Range
- The range.
Param | Type | Description |
---|---|---|
cell | Cell | string | The other cell or cell address to range to. |
Cell
Returns a cell with a relative position given the offsets provided.
Kind: instance method of Cell
Returns: Cell
- The relative cell.
Param | Type | Description |
---|---|---|
rowOffset | number | The row offset (0 for the current row). |
columnOffset | number | The column offset (0 for the current column). |
Row
Gets the parent row of the cell.
Kind: instance method of Cell
Returns: Row
- The parent row.
number
Gets the row number of the cell (1-based).
Kind: instance method of Cell
Returns: number
- The row number.
Sheet
Gets the parent sheet.
Kind: instance method of Cell
Returns: Sheet
- The parent sheet.
*
Gets an individual style.
Kind: instance method of Cell
Returns: *
- The style.
Param | Type | Description |
---|---|---|
name | string | The name of the style. |
object.<string, *>
Gets multiple styles.
Kind: instance method of Cell
Returns: object.<string, *>
- Object whose keys are the style names and values are the styles.
Param | Type | Description |
---|---|---|
names | Array.<string> | The names of the style. |
Cell
Sets an individual style.
Kind: instance method of Cell
Returns: Cell
- The cell.
Param | Type | Description |
---|---|---|
name | string | The name of the style. |
value | * | The value to set. |
Range
Sets the styles in the range starting with the cell.
Kind: instance method of Cell
Returns: Range
- The range that was set.
Param | Type | Description |
---|---|---|
name | string | The name of the style. |
Array.<Array.<*>> | 2D array of values to set. |
Cell
Sets multiple styles.
Kind: instance method of Cell
Returns: Cell
- The cell.
Param | Type | Description |
---|---|---|
styles | object.<string, *> | Object whose keys are the style names and values are the styles to set. |
Cell
Sets to a specific style
Kind: instance method of Cell
Returns: Cell
- The cell.
Param | Type | Description |
---|---|---|
style | Style | Style object given from stylesheet.createStyle |
string
| boolean
| number
| Date
| RichText
| undefined
Gets the value of the cell.
Kind: instance method of Cell
Returns: string
| boolean
| number
| Date
| RichText
| undefined
- The value of the cell.
Cell
Sets the value of the cell.
Kind: instance method of Cell
Returns: Cell
- The cell.
Param | Type | Description |
---|---|---|
value | string | boolean | number | null | undefined | RichText | The value to set. |
Range
Sets the values in the range starting with the cell.
Kind: instance method of Cell
Returns: Range
- The range that was set.
Param | Type | Description |
---|---|---|
Array.<Array.<(string|boolean|number|null|undefined)>> | 2D array of values to set. |
Workbook
Gets the parent workbook.
Kind: instance method of Cell
Returns: Workbook
- The parent workbook.
Cell
Append horizontal page break after the cell.
Kind: instance method of Cell
Returns: Cell
- the cell.
undefined
Callback used by tap.
Kind: inner typedef of Cell
Param | Type | Description |
---|---|---|
cell | Cell | The cell |
*
Callback used by thru.
Kind: inner typedef of Cell
Returns: *
- The value to return from thru.
Param | Type | Description |
---|---|---|
cell | Cell | The cell |
A column.
Kind: global class
string
Cell
string
number
boolean
Column
Sheet
*
object.<string, *>
Cell
Cell
Cell
undefined
| number
Column
Workbook
Column
string
Get the address of the column.
Kind: instance method of Column
Returns: string
- The address
Param | Type | Description |
---|---|---|
[opts] | Object | Options |
[opts.includeSheetName] | boolean | Include the sheet name in the address. |
[opts.anchored] | boolean | Anchor the address. |
Cell
Get a cell within the column.
Kind: instance method of Column
Returns: Cell
- The cell in the column with the given row number.
Param | Type | Description |
---|---|---|
rowNumber | number | The row number. |
string
Get the name of the column.
Kind: instance method of Column
Returns: string
- The column name.
number
Get the number of the column.
Kind: instance method of Column
Returns: number
- The column number.
boolean
Gets a value indicating whether the column is hidden.
Kind: instance method of Column
Returns: boolean
- A flag indicating whether the column is hidden.
Column
Sets whether the column is hidden.
Kind: instance method of Column
Returns: Column
- The column.
Param | Type | Description |
---|---|---|
hidden | boolean | A flag indicating whether to hide the column. |
Sheet
Get the parent sheet.
Kind: instance method of Column
Returns: Sheet
- The parent sheet.
*
Gets an individual style.
Kind: instance method of Column
Returns: *
- The style.
Param | Type | Description |
---|---|---|
name | string | The name of the style. |
object.<string, *>
Gets multiple styles.
Kind: instance method of Column
Returns: object.<string, *>
- Object whose keys are the style names and values are the styles.
Param | Type | Description |
---|---|---|
names | Array.<string> | The names of the style. |
Cell
Sets an individual style.
Kind: instance method of Column
Returns: Cell
- The cell.
Param | Type | Description |
---|---|---|
name | string | The name of the style. |
value | * | The value to set. |
Cell
Sets multiple styles.
Kind: instance method of Column
Returns: Cell
- The cell.
| Param | Type |
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 9/21 approved changesets -- score normalized to 4
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
76 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-12-23
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