ExcelJS-RTL
Read, manipulate and write spreadsheet data and styles to XLSX and JSON and now with RTL support.
Reverse engineered from Excel spreadsheet files as a project. based on exceljs.
Installation
npm install exceljs-rtl
New Features!
- RTL Support ('A' Column on the right side)
- Merged Stops Bluebird warning about unreturned promise #245. Thanks to robinbullocks4rb for the contribution.
- Merged Added missing dependency: col-cache.js #247. Thanks to Manish2005 for the contribution.
Contents
- Interface
- Value Types
- Known Issues
- Release History
Interface
var Excel = ;
Create a Workbook
var workbook = ;
Set Workbook Properties
workbookcreator = 'Me';workbooklastModifiedBy = 'Her';workbookcreated = 1985 8 30;workbookmodified = ;workbooklastPrinted = 2016 9 27;
// Set workbook dates to 1904 date systemworkbookpropertiesdate1904 = true;
Workbook Views
The Workbook views controls how many separate windows Excel will open when viewing the workbook.
workbookviews = x: 0 y: 0 width: 10000 height: 20000 firstSheet: 0 activeTab: 1 visibility: 'visible'
Add a Worksheet
var sheet = workbook;
Use the second parameter of the addWorksheet function to specify options for the worksheet.
For Example:
// create a sheet with red tab colourvar sheet = workbook; // create a sheet where the grid lines are hiddenvar sheet = workbook; // create a sheet(RTL - 'A' column on the right) with the first row and column frozenvar sheet = workbook;
Access Worksheets
// Iterate over all sheets// Note: workbook.worksheets.forEach will still work but this is betterworkbook; // fetch sheet by namevar worksheet = workbook; // fetch sheet by idvar worksheet = workbook;
Worksheet Properties
Worksheets support a property bucket to allow control over some features of the worksheet.
// create new sheet with propertiesvar worksheet = workbook; // create a new sheet writer with propertiesvar worksheetWriter = workbookWriter; // adjust properties afterwards (not supported by worksheet-writer)worksheetpropertiesoutlineLevelCol = 2;worksheetpropertiesdefaultRowHeight = 15;
Supported Properties
Name | Default | Description |
---|---|---|
tabColor | undefined | Color of the tabs |
outlineLevelCol | 0 | The worksheet column outline level |
outlineLevelRow | 0 | The worksheet row outline level |
defaultRowHeight | 15 | Default row height |
dyDescent | 55 | TBD |
Worksheet Metrics
Some new metrics have been added to Worksheet...
Name | Description |
---|---|
rowCount | The total row size of the document. Equal to the row number of the last row that has values. |
actualRowCount | A count of the number of rows that have values. If a mid-document row is empty, it will not be included in the count. |
columnCount | The total column size of the document. Equal to the maximum cell count from all of the rows |
actualColumnCount | A count of the number of columns that have values. |
Page Setup
All properties that can affect the printing of a sheet are held in a pageSetup object on the sheet.
// create new sheet with pageSetup settings for A4 - landscapevar worksheet = workbook; // create a new sheet writer with pageSetup settings for fit-to-pagevar worksheetWriter = workbookWriter; // adjust pageSetup settings afterwardsworksheetpageSetupmargins = left: 07 right: 07 top: 075 bottom: 075 header: 03 footer: 03; // Set Print Area for a sheetworksheetpageSetupprintArea = 'A1:G20';
Supported pageSetup settings
Name | Default | Description |
---|---|---|
margins | Whitespace on the borders of the page. Units are inches. | |
orientation | 'portrait' | Orientation of the page - i.e. taller (portrait) or wider (landscape) |
horizontalDpi | 4294967295 | Horizontal Dots per Inch. Default value is -1 |
verticalDpi | 4294967295 | Vertical Dots per Inch. Default value is -1 |
fitToPage | Whether to use fitToWidth and fitToHeight or scale settings. Default is based on presence of these settings in the pageSetup object - if both are present, scale wins (i.e. default will be false) | |
pageOrder | 'downThenOver' | Which order to print the pages - one of ['downThenOver', 'overThenDown'] |
blackAndWhite | false | Print without colour |
draft | false | Print with less quality (and ink) |
cellComments | 'None' | Where to place comments - one of ['atEnd', 'asDisplayed', 'None'] |
errors | 'displayed' | Where to show errors - one of ['dash', 'blank', 'NA', 'displayed'] |
scale | 100 | Percentage value to increase or reduce the size of the print. Active when fitToPage is false |
fitToWidth | 1 | How many pages wide the sheet should print on to. Active when fitToPage is true |
fitToHeight | 1 | How many pages high the sheet should print on to. Active when fitToPage is true |
paperSize | What paper size to use (see below) | |
showRowColHeaders | false | Whether to show the row numbers and column letters |
showGridLines | false | Whether to show grid lines |
firstPageNumber | Which number to use for the first page | |
horizontalCentered | false | Whether to center the sheet data horizontally |
verticalCentered | false | Whether to center the sheet data vertically |
Example Paper Sizes
Name | Value |
---|---|
Letter | undefined |
Legal | 5 |
Executive | 7 |
A4 | 9 |
A5 | 11 |
B5 (JIS) | 13 |
Envelope #10 | 20 |
Envelope DL | 27 |
Envelope C5 | 28 |
Envelope B5 | 34 |
Envelope Monarch | 37 |
Double Japan Postcard Rotated | 82 |
16K 197x273 mm | 119 |
Worksheet Views
Worksheets now support a list of views, that control how Excel presents the sheet:
- frozen - where a number of rows and columns to the top and left are frozen in place. Only the bottom left section will scroll
- split - where the view is split into 4 sections, each semi-independently scrollable.
Each view also supports various properties:
Name | Default | Description |
---|---|---|
state | 'normal' | Controls the view state - one of normal, frozen or split |
activeCell | undefined | The currently selected cell |
showRuler | true | Shows or hides the ruler in Page Layout |
showRowColHeaders | true | Shows or hides the row and column headers (e.g. A1, B1 at the top and 1,2,3 on the left |
showGridLines | true | Shows or hides the gridlines (shown for cells where borders have not been defined) |
zoomScale | 100 | Percentage zoom to use for the view |
zoomScaleNormal | 100 | Normal zoom for the view |
style | undefined | Presentation style - one of pageBreakPreview or pageLayout. Note pageLayout is not compatable with frozen views |
Frozen Views
Frozen views support the following extra properties:
Name | Default | Description |
---|---|---|
xSplit | 0 | How many columns to freeze. To freeze rows only, set this to 0 or undefined |
ySplit | 0 | How many rows to freeze. To freeze columns only, set this to 0 or undefined |
topLeftCell | special | Which cell will be top-left in the bottom-right pane. Note: cannot be a frozen cell. Defaults to first unfrozen cell |
worksheetviews = state: 'frozen' xSplit: 2 ySplit: 3 topLeftCell: 'G10' activeCell: 'A1';
Split Views
Split views support the following extra properties:
Name | Default | Description |
---|---|---|
xSplit | 0 | How many points from the left to place the splitter. To split vertically, set this to 0 or undefined |
ySplit | 0 | How many points from the top to place the splitter. To split horizontally, set this to 0 or undefined |
topLeftCell | undefined | Which cell will be top-left in the bottom-right pane. |
activePane | undefined | Which pane will be active - one of topLeft, topRight, bottomLeft and bottomRight |
worksheetviews = state: 'split' xSplit: 2000 ySplit: 3000 topLeftCell: 'G10' activeCell: 'A1';
Columns
// Add column headers and define column keys and widths// Note: these column structures are a workbook-building convenience only,// apart from the column width, they will not be fully persisted.worksheetcolumns = header: 'Id' key: 'id' width: 10 header: 'Name' key: 'name' width: 32 header: 'D.O.B.' key: 'DOB' width: 10 outlineLevel: 1 ; // Access an individual columns by key, letter and 1-based column numbervar idCol = worksheet;var nameCol = worksheet;var dobCol = worksheet; // set column properties // Note: will overwrite cell value C1dobColheader = 'Date of Birth'; // Note: this will overwrite cell values C1:C2dobColheader = 'Date of Birth' 'A.K.A. D.O.B.'; // from this point on, this column will be indexed by 'dob' and not 'DOB'dobColkey = 'dob'; dobColwidth = 15; // Hide the column if you'd likedobColhidden = true; // set an outline level for columnsworksheetoutlineLevel = 0;worksheetoutlineLevel = 1; // columns support a readonly field to indicate the collapsed state based on outlineLevelto;to; // iterate over all current cells in this columndobCol; // iterate over all current cells in this column including empty cellsdobCol; // cut one or more columns (columns to the right are shifted left)// If column properties have been definde, they will be cut or moved accordingly// Known Issue: If a splice causes any merged cells to move, the results may be unpredictableworksheet; // remove one column and insert two more.// Note: columns 4 and above will be shifted right by 1 column. // Also: If the worksheet has more rows than values in the colulmn inserts, // the rows will still be shifted as if the values existed var newCol3Values = 12345;var newCol4Values = 'one' 'two' 'three' 'four' 'five';worksheet;
Rows
// Add a couple of Rows by key-value, after the last current row, using the column keysworksheet;worksheet; // Add a row by contiguous Array (assign to columns A, B & C)worksheet; // Add a row by sparse Array (assign to columns A, E & I)var rowValues = ;rowValues1 = 4;rowValues5 = 'Kyle';rowValues9 = ;worksheet; // Add an array of rowsvar rows = 5'Bob' // row by array id:6 name: 'Barbara' dob: ;worksheet; // Get a row object. If it doesn't already exist, a new empty one will be returnedvar row = worksheet; // Get the last editable row in a worksheet (or undefined if there are none)var row = worksheetlastRow; // Set a specific row heightrowheight = 425; // make row hiddenrowhidden = true; // set an outline level for rowsworksheetoutlineLevel = 0;worksheetoutlineLevel = 1; // rows support a readonly field to indicate the collapsed state based on outlineLevelto;to; rowvalue = 5; // A5's value set to 5rowvalue = 'Zeb'; // B5's value set to 'Zeb' - assuming column 2 is still keyed by namerowvalue = ; // C5's value set to now // Get a row as a sparse array// Note: interface change: worksheet.getRow(4) ==> worksheet.getRow(4).valuesrow = worksheetvalues;; // assign row values by contiguous array (where array element 0 has a value)rowvalues = 123;;;; // assign row values by sparse array (where array element 0 is undefined)var values = values5 = 7;values10 = 'Hello, World!';rowvalues = values;;;; // assign row values by object, using column keysrowvalues = id: 13 name: 'Thing 1' dob: ; // Iterate over all rows that have values in a worksheetworksheet; // Iterate over all rows (including empty rows) in a worksheetworksheet; // Iterate over all non-null cells in a rowrow; // Iterate over all cells in a row (including empty cells)row; // Cut one or more rows (rows below are shifted up)// Known Issue: If a splice causes any merged cells to move, the results may be unpredictableworksheet; // remove one row and insert two more.// Note: rows 4 and below will be shifted down by 1 row. var newRow3Values = 12345;var newRow4Values = 'one' 'two' 'three' 'four' 'five';worksheet; // Cut one or more cells (cells to the right are shifted left)// Note: this operation will not affect other rowsrow; // remove one cell and insert two more (cells to the right of the cut cell will be shifted right)row; // Commit a completed row to streamrow; // row metricsvar rowSize = rowcellCount;var numValues = rowactualCellCount;
Handling Individual Cells
// Modify/Add individual cellworksheetvalue = 1968 5 1; // query a cell's type;
Merged Cells
// merge a range of cellsworksheet; // ... merged cells are linkedworksheetvalue = 'Hello, World!';;; // ... merged cells share the same style object;worksheetstylefont = myFontsarial;; // unmerging the cells breaks the style linksworksheet;not;not; // merge by top-left, bottom-rightworksheet;worksheet; // top,left,bottom,right
Defined Names
Individual cells (or multiple groups of cells) can have names assigned to them. The names can be used in formulas and data validation (and probably more).
// assign (or get) a name for a cell (will overwrite any other names that cell had)worksheetname = 'PI';to; // assign (or get) an array of names for a cell (cells can have more than one name)worksheetnames = 'thing1' 'thing2';tohave; // remove a name from a cellworksheet;tohave;
Data Validations
Cells can define what values are valid or not and provide prompting to the user to help guide them.
Validation types can be one of the following:
Type | Description |
---|---|
list | Define a discrete set of valid values. Excel will offer these in a dropdown for easy entry |
whole | The value must be a whole number |
decimal | The value must be a decimal number |
textLength | The value may be text but the length is controlled |
custom | A custom formula controls the valid values |
For types other than list or custom, the following operators affect the validation:
Operator | Description |
---|---|
between | Values must lie between formula results |
notBetween | Values must not lie between formula results |
equal | Value must equal formula result |
notEqual | Value must not equal formula result |
greaterThan | Value must be greater than formula result |
lessThan | Value must be less than formula result |
greaterThanOrEqual | Value must be greater than or equal to formula result |
lessThanOrEqual | Value must be less than or equal to formula result |
// Specify list of valid values (One, Two, Three, Four). Excel will provide a dropdown with these values.worksheetdataValidation = type: 'list' allowBlank: true formulae: '"One,Two,Three,Four"'; // Specify list of valid values from a range. Excel will provide a dropdown with these values. worksheetdataValidation = type: 'list' allowBlank: true formulae: '$D$5:$F$5'; // Specify Cell must be a whole number that is not 5. Show the user an appropriate error message if they get it wrongworksheetdataValidation = type: 'whole' operator: 'notEqual' showErrorMessage: true formulae: 5 errorStyle: 'error' errorTitle: 'Five' error: 'The value must not be Five'; // Specify Cell must be a decomal number between 1.5 and 7. Add 'tooltip' to help guid the userworksheetdataValidation = type: 'decimal' operator: 'between' allowBlank: true showInputMessage: true formulae: 15 7 promptTitle: 'Decimal' prompt: 'The value must between 1.5 and 7'; // Specify Cell must be have a text length less than 15worksheetdataValidation = type: 'textLength' operator: 'lessThan' showErrorMessage: true allowBlank: true formulae: 15; // Specify Cell must be have be a date before 1st Jan 2016worksheetdataValidation = type: 'date' operator: 'lessThan' showErrorMessage: true allowBlank: true formulae: 201601;
Styles
Cells, Rows and Columns each support a rich set of styles and formats that affect how the cells are displayed.
Styles are set by assigning the following properties:
// assign a style to a cellwsnumFmt = '0.00%'; // Apply styles to worksheet columnswscolumns = header: 'Id' key: 'id' width: 10 header: 'Name' key: 'name' width: 32 style: font: name: 'Arial Black' header: 'D.O.B.' key: 'DOB' width: 10 style: numFmt: 'dd/mm/yyyy' ; // Set Column 3 to Currency FormatwsnumFmt = '�#,##0;[Red]-�#,##0'; // Set Row 2 to Comic Sans.wsfont = name: 'Comic Sans MS' family: 4 size: 16 underline: 'double' bold: true ;
When a style is applied to a row or column, it will be applied to all currently existing cells in that row or column. Also, any new cell that is created will inherit its initial styles from the row and column it belongs to.
If a cell's row and column both define a specific style (e.g. font), the cell will use the row style over the column style. However if the row and column define different styles (e.g. column.numFmt and row.font), the cell will inherit the font from the row and the numFmt from the column.
Caveat: All the above properties (with the exception of numFmt, which is a string), are JS object structures. If the same style object is assigned to more than one spreadsheet entity, then each entity will share the same style object. If the style object is later modified before the spreadsheet is serialized, then all entities referencing that style object will be modified too. This behaviour is intended to prioritize performance by reducing the number of JS objects created. If you want the style objects to be independent, you will need to clone them before assigning them. Also, by default, when a document is read from file (or stream) if spreadsheet entities share similar styles, then they will reference the same style object too.
Number Formats
// display value as '1 3/5'wsvalue = 16;wsnumFmt = '# ?/?'; // display value as '1.60%'wsvalue = 0016;wsnumFmt = '0.00%';
Fonts
// for the wannabe graphic designers out therewsfont = name: 'Comic Sans MS' family: 4 size: 16 underline: true bold: true; // for the graduate graphic designers...wsfont = name: 'Arial Black' color: argb: 'FF00FF00' family: 2 size: 14 italic: true; // note: the cell will store a reference to the font object assigned.// If the font object is changed afterwards, the cell font will change also...var font = name: 'Arial' size: 12 ;wsfont = font;fontsize = 20; // Cell A3 now has font size 20! // Cells that share similar fonts may reference the same font object after// the workbook is read from file or stream
Font Property | Description | Example Value(s) |
---|---|---|
name | Font name. | 'Arial', 'Calibri', etc. |
family | Font family. An integer value. | 1,2,3, etc. |
scheme | Font scheme. | 'minor', 'major', 'none' |
charset | Font charset. An integer value. | 1, 2, 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 |
Alignment
// set cell alignment to top-left, middle-center, bottom-rightwsalignment = vertical: 'top' horizontal: 'left' ;wsalignment = vertical: 'middle' horizontal: 'center' ;wsalignment = vertical: 'bottom' horizontal: 'right' ; // set cell to wrap-textwsalignment = wrapText: true ; // set cell indent to 1wsalignment = indent: 1 ; // set cell text rotation to 30deg upwards, 45deg downwards and vertical textwsalignment = textRotation: 30 ;wsalignment = textRotation: -45 ;wsalignment = textRotation: 'vertical' ;
Valid Alignment Property Values
horizontal | vertical | wrapText | indent | readingOrder | textRotation |
---|---|---|---|---|---|
left | top | true | integer | rtl | 0 to 90 |
center | middle | false | ltr | -1 to -90 | |
right | bottom | vertical | |||
fill | distributed | ||||
justify | justify | ||||
centerContinuous | |||||
distributed |
Borders
// set single thin border around A1wsborder = top: style:'thin' left: style:'thin' bottom: style:'thin' right: style:'thin'; // set double thin green border around A3wsborder = top: style:'double' color: argb:'FF00FF00' left: style:'double' color: argb:'FF00FF00' bottom: style:'double' color: argb:'FF00FF00' right: style:'double' color: argb:'FF00FF00'; // set thick red cross in A5wsborder = diagonal: up: true down: true style:'thick' color: argb:'FFFF0000';
Valid Border Styles
- thin
- dotted
- dashDot
- hair
- dashDotDot
- slantDashDot
- mediumDashed
- mediumDashDotDot
- mediumDashDot
- medium
- double
- thick
Fills
// fill A1 with red darkVertical stripeswsfill = type: 'pattern' pattern:'darkVertical' fgColor:argb:'FFFF0000'; // fill A2 with yellow dark trellis and blue behindwsfill = type: 'pattern' pattern:'darkTrellis' fgColor:argb:'FFFFFF00' bgColor:argb:'FF0000FF'; // fill A3 with blue-white-blue gradient from left to rightwsfill = type: 'gradient' gradient: 'angle' degree: 0 stops: position:0 color:argb:'FF0000FF' position:05 color:argb:'FFFFFFFF' position:1 color:argb:'FF0000FF' ; // fill A4 with red-green gradient from centerwsfill = type: 'gradient' gradient: 'path' center:left:05top:05 stops: position:0 color:argb:'FFFF0000' position:1 color:argb:'FF00FF00' ;
Pattern Fills
Property | Required | Description |
---|---|---|
type | Y | Value: 'pattern' Specifies this fill uses patterns |
pattern | Y | Specifies type of pattern (see Valid Pattern Types below) |
fgColor | N | Specifies the pattern foreground color. Default is black. |
bgColor | N | Specifies the pattern background color. Default is white. |
Valid Pattern Types
- none
- solid
- darkVertical
- darkGray
- mediumGray
- lightGray
- gray125
- gray0625
- darkHorizontal
- darkVertical
- darkDown
- darkUp
- darkGrid
- darkTrellis
- lightHorizontal
- lightVertical
- lightDown
- lightUp
- lightGrid
- lightTrellis
- lightGrid
Gradient Fills
Property | Required | Description |
---|---|---|
type | Y | Value: 'gradient' Specifies this fill uses gradients |
gradient | Y | Specifies gradient type. One of ['angle', 'path'] |
degree | angle | For 'angle' gradient, specifies the direction of the gradient. 0 is from the left to the right. Values from 1 - 359 rotates the direction clockwise |
center | path | For 'path' gradient. Specifies the relative coordinates for the start of the path. 'left' and 'top' values range from 0 to 1 |
stops | Y | Specifies the gradient colour sequence. Is an array of objects containing position and color starting with position 0 and ending with position 1. Intermediatary positions may be used to specify other colours on the path. |
Caveats
Using the interface above it may be possible to create gradient fill effects not possible using the XLSX editor program. For example, Excel only supports angle gradients of 0, 45, 90 and 135. Similarly the sequence of stops may also be limited by the UI with positions [0,1] or [0,0.5,1] as the only options. Take care with this fill to be sure it is supported by the target XLSX viewers.
Rich Text
Individual cells now support rich text or in-cell formatting. Rich text values can control the font properties of any number of sub-strings within the text value. See Fonts for a complete list of details on what font properties are supported.
wsvalue = 'richText': 'font': 'size': 12'color': 'theme': 0'name': 'Calibri''family': 2'scheme': 'minor''text': 'This is ' 'font': 'italic': true'size': 12'color': 'theme': 0'name': 'Calibri''scheme': 'minor''text': 'a' 'font': 'size': 12'color': 'theme': 1'name': 'Calibri''family': 2'scheme': 'minor''text': ' ' 'font': 'size': 12'color': 'argb': 'FFFF6600''name': 'Calibri''scheme': 'minor''text': 'colorful' 'font': 'size': 12'color': 'theme': 1'name': 'Calibri''family': 2'scheme': 'minor''text': ' text ' 'font': 'size': 12'color': 'argb': 'FFCCFFCC''name': 'Calibri''scheme': 'minor''text': 'with' 'font': 'size': 12'color': 'theme': 1'name': 'Calibri''family': 2'scheme': 'minor''text': ' in-cell ' 'font': 'bold': true'size': 12'color': 'theme': 1'name': 'Calibri''family': 2'scheme': 'minor''text': 'format' ; to;to;
Outline Levels
Excel supports outlining; where rows or columns can be expanded or collapsed depending on what level of detail the user wishes to view.
Outline levels can be defined in column setup:
worksheetcolumns = header: 'Id' key: 'id' width: 10 header: 'Name' key: 'name' width: 32 header: 'D.O.B.' key: 'DOB' width: 10 outlineLevel: 1 ;
Or directly on the row or column
worksheetoutlineLevel = 1;worksheetoutlineLevel = 1;
The sheet outline levels can be set on the worksheet
// set column outline levelworksheetpropertiesoutlineLevelCol = 1; // set row outline levelworksheetpropertiesoutlineLevelRow = 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.:
worksheetpropertiesoutlineLevelCol = 1; worksheetoutlineLevel = 1;tobetrue; worksheetpropertiesoutlineLevelCol = 2;tobefalse;
File I/O
XLSX
Reading XLSX
// read from a filevar workbook = ;workbookxlsx ; // pipe from streamvar workbook = ;stream;
Writing XLSX
// write to a filevar workbook = ;workbookxlsx ; // write to a streamworkbookxlsx ;
CSV
Reading CSV
// read from a filevar workbook = ;workbookcsv ; // read from a streamvar workbook = ;workbookcsv ; // pipe from streamvar workbook = ;stream; // read from a file with European Datesvar workbook = ;var options = dateFormats: 'DD/MM/YYYY';workbookcsv ; // read from a file with custom value parsingvar workbook = ;var options = { };workbookcsv ;
The CSV parser uses fast-csv to read the CSV file. The options passed into the read functions above is also passed to fast-csv for parsing of the csv data. Please refer to the fast-csv README.md for details.
Dates are parsed using the npm module moment. If no dateFormats are supplied, the following are used:
- moment.ISO_8601
- 'MM-DD-YYYY'
- 'YYYY-MM-DD'
Writing CSV
// write to a filevar workbook = ;workbookcsv ; // write to a streamworkbookcsv ; // read from a file with European Date-Timesvar workbook = ;var options = dateFormat: 'DD/MM/YYYY HH:mm:ss';workbookcsv ; // read from a file with custom value formattingvar workbook = ;var options = { };workbookcsv ;
The CSV parser uses fast-csv to write the CSV file. The options passed into the write functions above is also passed to fast-csv for writing the csv data. Please refer to the fast-csv README.md for details.
Dates are formatted using the npm module moment. If no dateFormat is supplied, moment.ISO_8601 is used.
Streaming I/O
The File I/O documented above requires that an entire workbook is built up in memory before the file can be written. While convenient, it can limit the size of the document due to the amount of memory required.
A streaming writer (or reader) processes the workbook or worksheet data as it is generated, converting it into file form as it goes. Typically this is much more efficient on memory as the final memory footprint and even intermediate memory footprints are much more compact than with the document version, especially when you consider that the row and cell objects are disposed once they are committed.
The interface to the streaming workbook and worksheet is almost the same as the document versions with a few minor practical differences:
- Once a worksheet is added to a workbook, it cannot be removed.
- Once a row is committed, it is no longer accessible since it will have been dropped from the worksheet.
- unMergeCells() is not supported.
Note that it is possible to build the entire workbook without committing any rows. When the workbook is committed, all added worksheets (including all uncommitted rows) will be automatically committed. However in this case, little will have been gained over the Document version.
Streaming XLSX
Streaming XLSX Writer
The streaming XLSX writer is available in the ExcelJS.stream.xlsx namespace.
The constructor takes an optional options object with the following fields:
Field | Description |
---|---|
stream | Specifies a writable stream to write the XLSX workbook to. |
filename | If stream not specified, this field specifies the path to a file to write the XLSX workbook to. |
useSharedStrings | Specifies whether to use shared strings in the workbook. Default is false |
useStyles | Specifies whether to add style information to the workbook. Styles can add some performance overhead. Default is false |
If neither stream nor filename is specified in the options, the workbook writer will create a StreamBuf object that will store the contents of the XLSX workbook in memory. This StreamBuf object, which can be accessed via the property workbook.stream, can be used to either access the bytes directly by stream.read() or to pipe the contents to another stream.
// construct a streaming XLSX workbook writer with styles and shared stringsvar options = filename: './streamed-workbook.xlsx' useStyles: true useSharedStrings: true;var workbook = options;
In general, the interface to the streaming XLSX writer is the same as the Document workbook (and worksheets) described above, in fact the row, cell and style objects are the same.
However there are some differences...
Construction
As seen above, the WorkbookWriter will typically require the output stream or file to be specified in the constructor.
Committing Data
When a worksheet row is ready, it should be committed so that the row object and contents can be freed. Typically this would be done as each row is added...
worksheet;
The reason the WorksheetWriter does not commit rows as they are added is to allow cells to be merged across rows:
worksheet;worksheetvalue = 'I am merged';worksheetvalue = 'I am not';worksheetvalue = 'Neither am I';worksheet; // now rows 1 and two are committed.
As each worksheet is completed, it must also be committed:
// Finished adding data. Commit the worksheetworksheet;
To complete the XLSX document, the workbook must be committed. If any worksheet in a workbook are uncommitted, they will be committed automatically as part of the workbook commit.
// Finished the workbook.workbook ;
Value Types
The following value types are supported.
Enum Name | Enum | Description | Example Value |
---|---|---|---|
Excel.ValueType.Null | 0 | No value. | null |
Excel.ValueType.Merge | 1 | N/A | N/A |
Excel.ValueType.Number | 2 | A numerical value | 3.14 |
Excel.ValueType.String | 3 | A text value | 'Hello, World!' |
Excel.ValueType.Date | 4 | A Date value | new Date() |
Excel.ValueType.Hyperlink | 5 | A hyperlink | web: { text: 'www.mylink.com', hyperlink: 'http://www.mylink.com' } internal: { text: 'Sheet2', hyperlink: '#\'Sheet2\'!A1' } |
Excel.ValueType.Formula | 6 | A formula | { formula: 'A1+A2', result: 7 } |
Interface Changes
Every effort is made to make a good consistent interface that doesn't break through the versions but regrettably, now and then some things have to change for the greater good.
Interface Breaks in 0.1.0
Worksheet.eachRow
The arguments in the callback function to Worksheet.eachRow have been swapped and changed; it was function(rowNumber,rowValues), now it is function(row, rowNumber) which gives it a look and feel more like the underscore (_.each) function and prioritises the row object over the row number.
Worksheet.getRow
This function has changed from returning a sparse array of cell values to returning a Row object. This enables accessing row properties and will facilitate managing row styles and so on.
The sparse array of cell values is still available via Worksheet.getRow(rowNumber).values;
Interface Breaks in 0.1.1
cell.model
cell.styles renamed to cell.style
Known Issues
Splice vs Merge
If any splice operation affects a merged cell, the merge group will not be moved correctly
Release History
Version | Changes |
---|---|
0.0.9 | |
0.1.0 |
|
0.1.1 |
|
0.1.2 |
|
0.1.3 |
|
0.1.5 |
|
0.1.6 |
|
0.1.8 |
|
0.1.9 |
|
0.1.10 |
|
0.1.11 |
|
0.2.0 |
|
0.2.2 |
|
0.2.3 |
|
0.2.4 |
|
0.2.6 |
|
0.2.7 |
|
0.2.8 |
|
0.2.9 |
|
0.2.10 |
|
0.2.11 |
|
0.2.12 |
|
0.2.13 |
|
0.2.14 |
|
0.2.15 |
|
0.2.16 |
|
0.2.17 |
|
0.2.18 |
|
0.2.19 |
|
0.2.20 |
|
0.2.21 |
|
0.2.22 |
|
0.2.23 |
|
0.2.24 |
|
0.2.25 |
|
0.2.26 |
|
0.2.27 |
|
0.2.28 |
|
0.2.29 |
|
0.2.30 |
|
0.2.31 |
|
0.2.32 |
|
0.2.33 |
|
0.2.34 |
|
0.2.35 |
|
0.2.36 |
|
0.2.37 |
|
0.2.38 |
|