UNPKG

110 kBMarkdownView Raw
1# [SheetJS js-xlsx](http://sheetjs.com)
2
3Parser and writer for various spreadsheet formats. Pure-JS cleanroom
4implementation from official specifications, related documents, and test files.
5Emphasis on parsing and writing robustness, cross-format feature compatibility
6with a unified JS representation, and ES3/ES5 browser compatibility back to IE6.
7
8This is the community version. We also offer a pro version with performance
9enhancements, additional features like styling, and dedicated support.
10
11
12[**Pro Version**](http://sheetjs.com/pro)
13
14[**Commercial Support**](http://sheetjs.com/support)
15
16[**Rendered Documentation**](http://docs.sheetjs.com/)
17
18[**In-Browser Demos**](http://sheetjs.com/demos)
19
20[**Source Code**](http://git.io/xlsx)
21
22[**Issues and Bug Reports**](https://github.com/sheetjs/sheetjs/issues)
23
24[**File format support for known spreadsheet data formats:**](#file-formats)
25
26<details>
27 <summary><b>Graph of supported formats</b> (click to show)</summary>
28
29![circo graph of format support](formats.png)
30
31![graph legend](legend.png)
32
33</details>
34
35[**Browser Test**](http://oss.sheetjs.com/sheetjs/tests/)
36
37[![Build Status](https://saucelabs.com/browser-matrix/sheetjs.svg)](https://saucelabs.com/u/sheetjs)
38
39[![Build Status](https://travis-ci.org/SheetJS/sheetjs.svg?branch=master)](https://travis-ci.org/SheetJS/sheetjs)
40[![Build Status](https://semaphoreci.com/api/v1/sheetjs/sheetjs/branches/master/shields_badge.svg)](https://semaphoreci.com/sheetjs/sheetjs)
41[![Coverage Status](http://img.shields.io/coveralls/SheetJS/sheetjs/master.svg)](https://coveralls.io/r/SheetJS/sheetjs?branch=master)
42[![Dependencies Status](https://david-dm.org/sheetjs/sheetjs/status.svg)](https://david-dm.org/sheetjs/sheetjs)
43[![npm Downloads](https://img.shields.io/npm/dt/xlsx.svg)](https://npmjs.org/package/xlsx)
44[![Analytics](https://ga-beacon.appspot.com/UA-36810333-1/SheetJS/sheetjs?pixel)](https://github.com/SheetJS/sheetjs)
45
46## Table of Contents
47
48<details>
49 <summary><b>Expand to show Table of Contents</b></summary>
50
51<!-- toc -->
52
53- [Installation](#installation)
54 * [JS Ecosystem Demos](#js-ecosystem-demos)
55 * [Optional Modules](#optional-modules)
56 * [ECMAScript 5 Compatibility](#ecmascript-5-compatibility)
57- [Philosophy](#philosophy)
58- [Parsing Workbooks](#parsing-workbooks)
59 * [Parsing Examples](#parsing-examples)
60 * [Streaming Read](#streaming-read)
61- [Working with the Workbook](#working-with-the-workbook)
62 * [Parsing and Writing Examples](#parsing-and-writing-examples)
63- [Writing Workbooks](#writing-workbooks)
64 * [Writing Examples](#writing-examples)
65 * [Streaming Write](#streaming-write)
66- [Interface](#interface)
67 * [Parsing functions](#parsing-functions)
68 * [Writing functions](#writing-functions)
69 * [Utilities](#utilities)
70- [Common Spreadsheet Format](#common-spreadsheet-format)
71 * [General Structures](#general-structures)
72 * [Cell Object](#cell-object)
73 + [Data Types](#data-types)
74 + [Dates](#dates)
75 * [Sheet Objects](#sheet-objects)
76 + [Worksheet Object](#worksheet-object)
77 + [Chartsheet Object](#chartsheet-object)
78 + [Macrosheet Object](#macrosheet-object)
79 + [Dialogsheet Object](#dialogsheet-object)
80 * [Workbook Object](#workbook-object)
81 + [Workbook File Properties](#workbook-file-properties)
82 * [Workbook-Level Attributes](#workbook-level-attributes)
83 + [Defined Names](#defined-names)
84 + [Workbook Views](#workbook-views)
85 + [Miscellaneous Workbook Properties](#miscellaneous-workbook-properties)
86 * [Document Features](#document-features)
87 + [Formulae](#formulae)
88 + [Column Properties](#column-properties)
89 + [Row Properties](#row-properties)
90 + [Number Formats](#number-formats)
91 + [Hyperlinks](#hyperlinks)
92 + [Cell Comments](#cell-comments)
93 + [Sheet Visibility](#sheet-visibility)
94 + [VBA and Macros](#vba-and-macros)
95- [Parsing Options](#parsing-options)
96 * [Input Type](#input-type)
97 * [Guessing File Type](#guessing-file-type)
98- [Writing Options](#writing-options)
99 * [Supported Output Formats](#supported-output-formats)
100 * [Output Type](#output-type)
101- [Utility Functions](#utility-functions)
102 * [Array of Arrays Input](#array-of-arrays-input)
103 * [Array of Objects Input](#array-of-objects-input)
104 * [HTML Table Input](#html-table-input)
105 * [Formulae Output](#formulae-output)
106 * [Delimiter-Separated Output](#delimiter-separated-output)
107 + [UTF-16 Unicode Text](#utf-16-unicode-text)
108 * [HTML Output](#html-output)
109 * [JSON](#json)
110- [File Formats](#file-formats)
111 * [Excel 2007+ XML (XLSX/XLSM)](#excel-2007-xml-xlsxxlsm)
112 * [Excel 2.0-95 (BIFF2/BIFF3/BIFF4/BIFF5)](#excel-20-95-biff2biff3biff4biff5)
113 * [Excel 97-2004 Binary (BIFF8)](#excel-97-2004-binary-biff8)
114 * [Excel 2003-2004 (SpreadsheetML)](#excel-2003-2004-spreadsheetml)
115 * [Excel 2007+ Binary (XLSB, BIFF12)](#excel-2007-binary-xlsb-biff12)
116 * [Delimiter-Separated Values (CSV/TXT)](#delimiter-separated-values-csvtxt)
117 * [Other Workbook Formats](#other-workbook-formats)
118 + [Lotus 1-2-3 (WKS/WK1/WK2/WK3/WK4/123)](#lotus-1-2-3-wkswk1wk2wk3wk4123)
119 + [Quattro Pro (WQ1/WQ2/WB1/WB2/WB3/QPW)](#quattro-pro-wq1wq2wb1wb2wb3qpw)
120 + [OpenDocument Spreadsheet (ODS/FODS)](#opendocument-spreadsheet-odsfods)
121 + [Uniform Office Spreadsheet (UOS1/2)](#uniform-office-spreadsheet-uos12)
122 * [Other Single-Worksheet Formats](#other-single-worksheet-formats)
123 + [dBASE and Visual FoxPro (DBF)](#dbase-and-visual-foxpro-dbf)
124 + [Symbolic Link (SYLK)](#symbolic-link-sylk)
125 + [Lotus Formatted Text (PRN)](#lotus-formatted-text-prn)
126 + [Data Interchange Format (DIF)](#data-interchange-format-dif)
127 + [HTML](#html)
128 + [Rich Text Format (RTF)](#rich-text-format-rtf)
129 + [Ethercalc Record Format (ETH)](#ethercalc-record-format-eth)
130- [Testing](#testing)
131 * [Node](#node)
132 * [Browser](#browser)
133 * [Tested Environments](#tested-environments)
134 * [Test Files](#test-files)
135- [Contributing](#contributing)
136 * [OSX/Linux](#osxlinux)
137 * [Windows](#windows)
138 * [Tests](#tests)
139- [License](#license)
140- [References](#references)
141
142<!-- tocstop -->
143
144</details>
145
146## Installation
147
148In the browser, just add a script tag:
149
150```html
151<script lang="javascript" src="dist/xlsx.full.min.js"></script>
152```
153
154<details>
155 <summary><b>CDN Availability</b> (click to show)</summary>
156
157| CDN | URL |
158|-----------:|:-------------------------------------------|
159| `unpkg` | <https://unpkg.com/xlsx/> |
160| `jsDelivr` | <https://jsdelivr.com/package/npm/xlsx> |
161| `CDNjs` | <http://cdnjs.com/libraries/xlsx> |
162| `packd` | <https://bundle.run/xlsx@latest?name=XLSX> |
163
164`unpkg` makes the latest version available at:
165
166```html
167<script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
168```
169
170</details>
171
172
173With [npm](https://www.npmjs.org/package/xlsx):
174
175```bash
176$ npm install xlsx
177```
178
179With [bower](http://bower.io/search/?q=js-xlsx):
180
181```bash
182$ bower install js-xlsx
183```
184
185### JS Ecosystem Demos
186
187The [`demos` directory](demos/) includes sample projects for:
188
189**Frameworks and APIs**
190- [`angularjs`](demos/angular/)
191- [`angular 2 / 4 / 5 / 6 and ionic`](demos/angular2/)
192- [`knockout`](demos/knockout/)
193- [`meteor`](demos/meteor/)
194- [`react and react-native`](demos/react/)
195- [`vue 2.x and weex`](demos/vue/)
196- [`XMLHttpRequest and fetch`](demos/xhr/)
197- [`nodejs server`](demos/server/)
198- [`databases and key/value stores`](demos/database/)
199- [`typed arrays and math`](demos/array/)
200
201**Bundlers and Tooling**
202- [`browserify`](demos/browserify/)
203- [`fusebox`](demos/fusebox/)
204- [`parcel`](demos/parcel/)
205- [`requirejs`](demos/requirejs/)
206- [`rollup`](demos/rollup/)
207- [`systemjs`](demos/systemjs/)
208- [`typescript`](demos/typescript/)
209- [`webpack 2.x`](demos/webpack/)
210
211**Platforms and Integrations**
212- [`electron application`](demos/electron/)
213- [`nw.js application`](demos/nwjs/)
214- [`Chrome / Chromium extensions`](demos/chrome/)
215- [`Adobe ExtendScript`](demos/extendscript/)
216- [`Headless Browsers`](demos/headless/)
217- [`canvas-datagrid`](demos/datagrid/)
218- [`Swift JSC and other engines`](demos/altjs/)
219- [`"serverless" functions`](demos/function/)
220- [`internet explorer`](demos/oldie/)
221
222Other examples are included in the [showcase](demos/showcase/).
223
224### Optional Modules
225
226<details>
227 <summary><b>Optional features</b> (click to show)</summary>
228
229The node version automatically requires modules for additional features. Some
230of these modules are rather large in size and are only needed in special
231circumstances, so they do not ship with the core. For browser use, they must
232be included directly:
233
234```html
235<!-- international support from js-codepage -->
236<script src="dist/cpexcel.js"></script>
237```
238
239An appropriate version for each dependency is included in the dist/ directory.
240
241The complete single-file version is generated at `dist/xlsx.full.min.js`
242
243A slimmer build with XLSX / HTML support is generated at `dist/xlsx.mini.min.js`
244
245Webpack and Browserify builds include optional modules by default. Webpack can
246be configured to remove support with `resolve.alias`:
247
248```js
249 /* uncomment the lines below to remove support */
250 resolve: {
251 alias: { "./dist/cpexcel.js": "" } // <-- omit international support
252 }
253```
254
255</details>
256
257### ECMAScript 5 Compatibility
258
259Since the library uses functions like `Array#forEach`, older browsers require
260[shims to provide missing functions](http://oss.sheetjs.com/js-xlsx/shim.js).
261
262To use the shim, add the shim before the script tag that loads `xlsx.js`:
263
264```html
265<!-- add the shim first -->
266<script type="text/javascript" src="shim.min.js"></script>
267<!-- after the shim is referenced, add the library -->
268<script type="text/javascript" src="xlsx.full.min.js"></script>
269```
270
271The script also includes `IE_LoadFile` and `IE_SaveFile` for loading and saving
272files in Internet Explorer versions 6-9. The `xlsx.extendscript.js` script
273bundles the shim in a format suitable for Photoshop and other Adobe products.
274
275## Philosophy
276
277<details>
278 <summary><b>Philosophy</b> (click to show)</summary>
279
280Prior to SheetJS, APIs for processing spreadsheet files were format-specific.
281Third-party libraries either supported one format, or they involved a separate
282set of classes for each supported file type. Even though XLSB was introduced in
283Excel 2007, nothing outside of SheetJS or Excel supported the format.
284
285To promote a format-agnostic view, js-xlsx starts from a pure-JS representation
286that we call the ["Common Spreadsheet Format"](#common-spreadsheet-format).
287Emphasizing a uniform object representation enables new features like format
288conversion (reading an XLSX template and saving as XLS) and circumvents the
289"class trap". By abstracting the complexities of the various formats, tools
290need not worry about the specific file type!
291
292A simple object representation combined with careful coding practices enables
293use cases in older browsers and in alternative environments like ExtendScript
294and Web Workers. It is always tempting to use the latest and greatest features,
295but they tend to require the latest versions of browsers, limiting usability.
296
297Utility functions capture common use cases like generating JS objects or HTML.
298Most simple operations should only require a few lines of code. More complex
299operations generally should be straightforward to implement.
300
301Excel pushes the XLSX format as default starting in Excel 2007. However, there
302are other formats with more appealing properties. For example, the XLSB format
303is spiritually similar to XLSX but files often tend up taking less than half the
304space and open much faster! Even though an XLSX writer is available, other
305format writers are available so users can take advantage of the unique
306characteristics of each format.
307
308The primary focus of the Community Edition is correct data interchange, focused
309on extracting data from any compatible data representation and exporting data in
310various formats suitable for any third party interface.
311
312</details>
313
314## Parsing Workbooks
315
316For parsing, the first step is to read the file. This involves acquiring the
317data and feeding it into the library. Here are a few common scenarios:
318
319<details>
320 <summary><b>nodejs read a file</b> (click to show)</summary>
321
322`readFile` is only available in server environments. Browsers have no API for
323reading arbitrary files given a path, so another strategy must be used.
324
325```js
326if(typeof require !== 'undefined') XLSX = require('xlsx');
327var workbook = XLSX.readFile('test.xlsx');
328/* DO SOMETHING WITH workbook HERE */
329```
330
331</details>
332
333<details>
334 <summary><b>Photoshop ExtendScript read a file</b> (click to show)</summary>
335
336`readFile` wraps the `File` logic in Photoshop and other ExtendScript targets.
337The specified path should be an absolute path:
338
339```js
340#include "xlsx.extendscript.js"
341/* Read test.xlsx from the Documents folder */
342var workbook = XLSX.readFile(Folder.myDocuments + '/' + 'test.xlsx');
343/* DO SOMETHING WITH workbook HERE */
344```
345
346The [`extendscript` demo](demos/extendscript/) includes a more complex example.
347
348</details>
349
350<details>
351 <summary><b>Browser read TABLE element from page</b> (click to show)</summary>
352
353The `table_to_book` and `table_to_sheet` utility functions take a DOM TABLE
354element and iterate through the child nodes.
355
356```js
357var workbook = XLSX.utils.table_to_book(document.getElementById('tableau'));
358/* DO SOMETHING WITH workbook HERE */
359```
360
361Multiple tables on a web page can be converted to individual worksheets:
362
363```js
364/* create new workbook */
365var workbook = XLSX.utils.book_new();
366
367/* convert table 'table1' to worksheet named "Sheet1" */
368var ws1 = XLSX.utils.table_to_sheet(document.getElementById('table1'));
369XLSX.utils.book_append_sheet(workbook, ws1, "Sheet1");
370
371/* convert table 'table2' to worksheet named "Sheet2" */
372var ws2 = XLSX.utils.table_to_sheet(document.getElementById('table2'));
373XLSX.utils.book_append_sheet(workbook, ws2, "Sheet2");
374
375/* workbook now has 2 worksheets */
376```
377
378Alternatively, the HTML code can be extracted and parsed:
379
380```js
381var htmlstr = document.getElementById('tableau').outerHTML;
382var workbook = XLSX.read(htmlstr, {type:'string'});
383```
384
385</details>
386
387<details>
388 <summary><b>Browser download file (ajax)</b> (click to show)</summary>
389
390Note: for a more complete example that works in older browsers, check the demo
391at <http://oss.sheetjs.com/js-xlsx/ajax.html>. The [`xhr` demo](demos/xhr/)
392includes more examples with `XMLHttpRequest` and `fetch`.
393
394```js
395var url = "http://oss.sheetjs.com/test_files/formula_stress_test.xlsx";
396
397/* set up async GET request */
398var req = new XMLHttpRequest();
399req.open("GET", url, true);
400req.responseType = "arraybuffer";
401
402req.onload = function(e) {
403 var data = new Uint8Array(req.response);
404 var workbook = XLSX.read(data, {type:"array"});
405
406 /* DO SOMETHING WITH workbook HERE */
407}
408
409req.send();
410```
411
412</details>
413
414<details>
415 <summary><b>Browser drag-and-drop</b> (click to show)</summary>
416
417Drag-and-drop uses the HTML5 `FileReader` API.
418
419```js
420function handleDrop(e) {
421 e.stopPropagation(); e.preventDefault();
422 var files = e.dataTransfer.files, f = files[0];
423 var reader = new FileReader();
424 reader.onload = function(e) {
425 var data = new Uint8Array(e.target.result);
426 var workbook = XLSX.read(data, {type: 'array'});
427
428 /* DO SOMETHING WITH workbook HERE */
429 };
430 reader.readAsArrayBuffer(f);
431}
432drop_dom_element.addEventListener('drop', handleDrop, false);
433```
434
435</details>
436
437<details>
438 <summary><b>Browser file upload form element</b> (click to show)</summary>
439
440Data from file input elements can be processed using the same `FileReader` API
441as in the drag-and-drop example:
442
443```js
444function handleFile(e) {
445 var files = e.target.files, f = files[0];
446 var reader = new FileReader();
447 reader.onload = function(e) {
448 var data = new Uint8Array(e.target.result);
449 var workbook = XLSX.read(data, {type: 'array'});
450
451 /* DO SOMETHING WITH workbook HERE */
452 };
453 reader.readAsArrayBuffer(f);
454}
455input_dom_element.addEventListener('change', handleFile, false);
456```
457
458The [`oldie` demo](demos/oldie/) shows an IE-compatible fallback scenario.
459
460</details>
461
462More specialized cases, including mobile app file processing, are covered in the
463[included demos](demos/)
464
465### Parsing Examples
466
467- <http://oss.sheetjs.com/js-xlsx/> HTML5 File API / Base64 Text / Web Workers
468
469Note that older versions of IE do not support HTML5 File API, so the Base64 mode
470is used for testing.
471
472<details>
473 <summary><b>Get Base64 encoding on OSX / Windows</b> (click to show)</summary>
474
475On OSX you can get the Base64 encoding with:
476
477```bash
478$ <target_file base64 | pbcopy
479```
480
481On Windows XP and up you can get the Base64 encoding using `certutil`:
482
483```cmd
484> certutil -encode target_file target_file.b64
485```
486
487(note: You have to open the file and remove the header and footer lines)
488
489</details>
490
491- <http://oss.sheetjs.com/js-xlsx/ajax.html> XMLHttpRequest
492
493### Streaming Read
494
495<details>
496 <summary><b>Why is there no Streaming Read API?</b> (click to show)</summary>
497
498The most common and interesting formats (XLS, XLSX/M, XLSB, ODS) are ultimately
499ZIP or CFB containers of files. Neither format puts the directory structure at
500the beginning of the file: ZIP files place the Central Directory records at the
501end of the logical file, while CFB files can place the storage info anywhere in
502the file! As a result, to properly handle these formats, a streaming function
503would have to buffer the entire file before commencing. That belies the
504expectations of streaming, so we do not provide any streaming read API.
505
506</details>
507
508When dealing with Readable Streams, the easiest approach is to buffer the stream
509and process the whole thing at the end. This can be done with a temporary file
510or by explicitly concatenating the stream:
511
512<details>
513 <summary><b>Explicitly concatenating streams</b> (click to show)</summary>
514
515```js
516var fs = require('fs');
517var XLSX = require('xlsx');
518function process_RS(stream/*:ReadStream*/, cb/*:(wb:Workbook)=>void*/)/*:void*/{
519 var buffers = [];
520 stream.on('data', function(data) { buffers.push(data); });
521 stream.on('end', function() {
522 var buffer = Buffer.concat(buffers);
523 var workbook = XLSX.read(buffer, {type:"buffer"});
524
525 /* DO SOMETHING WITH workbook IN THE CALLBACK */
526 cb(workbook);
527 });
528}
529```
530
531More robust solutions are available using modules like `concat-stream`.
532
533</details>
534
535<details>
536 <summary><b>Writing to filesystem first</b> (click to show)</summary>
537
538This example uses [`tempfile`](https://npm.im/tempfile) to generate file names:
539
540```js
541var fs = require('fs'), tempfile = require('tempfile');
542var XLSX = require('xlsx');
543function process_RS(stream/*:ReadStream*/, cb/*:(wb:Workbook)=>void*/)/*:void*/{
544 var fname = tempfile('.sheetjs');
545 console.log(fname);
546 var ostream = fs.createWriteStream(fname);
547 stream.pipe(ostream);
548 ostream.on('finish', function() {
549 var workbook = XLSX.readFile(fname);
550 fs.unlinkSync(fname);
551
552 /* DO SOMETHING WITH workbook IN THE CALLBACK */
553 cb(workbook);
554 });
555}
556```
557
558</details>
559
560## Working with the Workbook
561
562The full object format is described later in this README.
563
564<details>
565 <summary><b>Reading a specific cell </b> (click to show)</summary>
566
567This example extracts the value stored in cell A1 from the first worksheet:
568
569```js
570var first_sheet_name = workbook.SheetNames[0];
571var address_of_cell = 'A1';
572
573/* Get worksheet */
574var worksheet = workbook.Sheets[first_sheet_name];
575
576/* Find desired cell */
577var desired_cell = worksheet[address_of_cell];
578
579/* Get the value */
580var desired_value = (desired_cell ? desired_cell.v : undefined);
581```
582
583</details>
584
585<details>
586 <summary><b>Adding a new worksheet to a workbook</b> (click to show)</summary>
587
588This example uses [`XLSX.utils.aoa_to_sheet`](#array-of-arrays-input) to make a
589sheet and `XLSX.utils.book_append_sheet` to append the sheet to the workbook:
590
591```js
592var ws_name = "SheetJS";
593
594/* make worksheet */
595var ws_data = [
596 [ "S", "h", "e", "e", "t", "J", "S" ],
597 [ 1 , 2 , 3 , 4 , 5 ]
598];
599var ws = XLSX.utils.aoa_to_sheet(ws_data);
600
601/* Add the worksheet to the workbook */
602XLSX.utils.book_append_sheet(wb, ws, ws_name);
603```
604
605</details>
606
607<details>
608 <summary><b>Creating a new workbook from scratch</b> (click to show)</summary>
609
610The workbook object contains a `SheetNames` array of names and a `Sheets` object
611mapping sheet names to sheet objects. The `XLSX.utils.book_new` utility function
612creates a new workbook object:
613
614```js
615/* create a new blank workbook */
616var wb = XLSX.utils.book_new();
617```
618
619The new workbook is blank and contains no worksheets. The write functions will
620error if the workbook is empty.
621
622</details>
623
624
625### Parsing and Writing Examples
626
627- <http://sheetjs.com/demos/modify.html> read + modify + write files
628
629- <https://github.com/SheetJS/js-xlsx/blob/master/bin/xlsx.njs> node
630
631The node version installs a command line tool `xlsx` which can read spreadsheet
632files and output the contents in various formats. The source is available at
633`xlsx.njs` in the bin directory.
634
635Some helper functions in `XLSX.utils` generate different views of the sheets:
636
637- `XLSX.utils.sheet_to_csv` generates CSV
638- `XLSX.utils.sheet_to_txt` generates UTF16 Formatted Text
639- `XLSX.utils.sheet_to_html` generates HTML
640- `XLSX.utils.sheet_to_json` generates an array of objects
641- `XLSX.utils.sheet_to_formulae` generates a list of formulae
642
643## Writing Workbooks
644
645For writing, the first step is to generate output data. The helper functions
646`write` and `writeFile` will produce the data in various formats suitable for
647dissemination. The second step is to actual share the data with the end point.
648Assuming `workbook` is a workbook object:
649
650<details>
651 <summary><b>nodejs write a file</b> (click to show)</summary>
652
653`XLSX.writeFile` uses `fs.writeFileSync` in server environments:
654
655```js
656if(typeof require !== 'undefined') XLSX = require('xlsx');
657/* output format determined by filename */
658XLSX.writeFile(workbook, 'out.xlsb');
659/* at this point, out.xlsb is a file that you can distribute */
660```
661
662</details>
663
664<details>
665 <summary><b>Photoshop ExtendScript write a file</b> (click to show)</summary>
666
667`writeFile` wraps the `File` logic in Photoshop and other ExtendScript targets.
668The specified path should be an absolute path:
669
670```js
671#include "xlsx.extendscript.js"
672/* output format determined by filename */
673XLSX.writeFile(workbook, 'out.xlsx');
674/* at this point, out.xlsx is a file that you can distribute */
675```
676
677The [`extendscript` demo](demos/extendscript/) includes a more complex example.
678
679</details>
680
681<details>
682 <summary><b>Browser add TABLE element to page</b> (click to show)</summary>
683
684The `sheet_to_html` utility function generates HTML code that can be added to
685any DOM element.
686
687```js
688var worksheet = workbook.Sheets[workbook.SheetNames[0]];
689var container = document.getElementById('tableau');
690container.innerHTML = XLSX.utils.sheet_to_html(worksheet);
691```
692
693</details>
694
695<details>
696 <summary><b>Browser upload file (ajax)</b> (click to show)</summary>
697
698A complete example using XHR is [included in the XHR demo](demos/xhr/), along
699with examples for fetch and wrapper libraries. This example assumes the server
700can handle Base64-encoded files (see the demo for a basic nodejs server):
701
702```js
703/* in this example, send a base64 string to the server */
704var wopts = { bookType:'xlsx', bookSST:false, type:'base64' };
705
706var wbout = XLSX.write(workbook,wopts);
707
708var req = new XMLHttpRequest();
709req.open("POST", "/upload", true);
710var formdata = new FormData();
711formdata.append('file', 'test.xlsx'); // <-- server expects `file` to hold name
712formdata.append('data', wbout); // <-- `data` holds the base64-encoded data
713req.send(formdata);
714```
715
716</details>
717
718<details>
719 <summary><b>Browser save file</b> (click to show)</summary>
720
721`XLSX.writeFile` wraps a few techniques for triggering a file save:
722
723- `URL` browser API creates an object URL for the file, which the library uses
724 by creating a link and forcing a click. It is supported in modern browsers.
725- `msSaveBlob` is an IE10+ API for triggering a file save.
726- `IE_FileSave` uses VBScript and ActiveX to write a file in IE6+ for Windows
727 XP and Windows 7. The shim must be included in the containing HTML page.
728
729There is no standard way to determine if the actual file has been downloaded.
730
731```js
732/* output format determined by filename */
733XLSX.writeFile(workbook, 'out.xlsb');
734/* at this point, out.xlsb will have been downloaded */
735```
736
737</details>
738
739<details>
740 <summary><b>Browser save file (compatibility)</b> (click to show)</summary>
741
742`XLSX.writeFile` techniques work for most modern browsers as well as older IE.
743For much older browsers, there are workarounds implemented by wrapper libraries.
744
745[`FileSaver.js`](https://github.com/eligrey/FileSaver.js/) implements `saveAs`.
746Note: `XLSX.writeFile` will automatically call `saveAs` if available.
747
748```js
749/* bookType can be any supported output type */
750var wopts = { bookType:'xlsx', bookSST:false, type:'array' };
751
752var wbout = XLSX.write(workbook,wopts);
753
754/* the saveAs call downloads a file on the local machine */
755saveAs(new Blob([wbout],{type:"application/octet-stream"}), "test.xlsx");
756```
757
758[`Downloadify`](https://github.com/dcneiner/downloadify) uses a Flash SWF button
759to generate local files, suitable for environments where ActiveX is unavailable:
760
761```js
762Downloadify.create(id,{
763 /* other options are required! read the downloadify docs for more info */
764 filename: "test.xlsx",
765 data: function() { return XLSX.write(wb, {bookType:"xlsx", type:'base64'}); },
766 append: false,
767 dataType: 'base64'
768});
769```
770
771The [`oldie` demo](demos/oldie/) shows an IE-compatible fallback scenario.
772
773</details>
774
775The [included demos](demos/) cover mobile apps and other special deployments.
776
777### Writing Examples
778
779- <http://sheetjs.com/demos/table.html> exporting an HTML table
780- <http://sheetjs.com/demos/writexlsx.html> generates a simple file
781
782### Streaming Write
783
784The streaming write functions are available in the `XLSX.stream` object. They
785take the same arguments as the normal write functions but return a Readable
786Stream. They are only exposed in NodeJS.
787
788- `XLSX.stream.to_csv` is the streaming version of `XLSX.utils.sheet_to_csv`.
789- `XLSX.stream.to_html` is the streaming version of `XLSX.utils.sheet_to_html`.
790- `XLSX.stream.to_json` is the streaming version of `XLSX.utils.sheet_to_json`.
791
792<details>
793 <summary><b>nodejs convert to CSV and write file</b> (click to show)</summary>
794
795```js
796var output_file_name = "out.csv";
797var stream = XLSX.stream.to_csv(worksheet);
798stream.pipe(fs.createWriteStream(output_file_name));
799```
800
801</details>
802
803<details>
804 <summary><b>nodejs write JSON stream to screen</b> (click to show)</summary>
805
806```js
807/* to_json returns an object-mode stream */
808var stream = XLSX.stream.to_json(worksheet, {raw:true});
809
810/* the following stream converts JS objects to text via JSON.stringify */
811var conv = new Transform({writableObjectMode:true});
812conv._transform = function(obj, e, cb){ cb(null, JSON.stringify(obj) + "\n"); };
813
814stream.pipe(conv); conv.pipe(process.stdout);
815```
816
817</details>
818
819<https://github.com/sheetjs/sheetaki> pipes write streams to nodejs response.
820
821## Interface
822
823`XLSX` is the exposed variable in the browser and the exported node variable
824
825`XLSX.version` is the version of the library (added by the build script).
826
827`XLSX.SSF` is an embedded version of the [format library](http://git.io/ssf).
828
829### Parsing functions
830
831`XLSX.read(data, read_opts)` attempts to parse `data`.
832
833`XLSX.readFile(filename, read_opts)` attempts to read `filename` and parse.
834
835Parse options are described in the [Parsing Options](#parsing-options) section.
836
837### Writing functions
838
839`XLSX.write(wb, write_opts)` attempts to write the workbook `wb`
840
841`XLSX.writeFile(wb, filename, write_opts)` attempts to write `wb` to `filename`.
842In browser-based environments, it will attempt to force a client-side download.
843
844`XLSX.writeFileAsync(filename, wb, o, cb)` attempts to write `wb` to `filename`.
845If `o` is omitted, the writer will use the third argument as the callback.
846
847`XLSX.stream` contains a set of streaming write functions.
848
849Write options are described in the [Writing Options](#writing-options) section.
850
851### Utilities
852
853Utilities are available in the `XLSX.utils` object and are described in the
854[Utility Functions](#utility-functions) section:
855
856**Importing:**
857
858- `aoa_to_sheet` converts an array of arrays of JS data to a worksheet.
859- `json_to_sheet` converts an array of JS objects to a worksheet.
860- `table_to_sheet` converts a DOM TABLE element to a worksheet.
861- `sheet_add_aoa` adds an array of arrays of JS data to an existing worksheet.
862- `sheet_add_json` adds an array of JS objects to an existing worksheet.
863
864
865**Exporting:**
866
867- `sheet_to_json` converts a worksheet object to an array of JSON objects.
868- `sheet_to_csv` generates delimiter-separated-values output.
869- `sheet_to_txt` generates UTF16 formatted text.
870- `sheet_to_html` generates HTML output.
871- `sheet_to_formulae` generates a list of the formulae (with value fallbacks).
872
873
874**Cell and cell address manipulation:**
875
876- `format_cell` generates the text value for a cell (using number formats).
877- `encode_row / decode_row` converts between 0-indexed rows and 1-indexed rows.
878- `encode_col / decode_col` converts between 0-indexed columns and column names.
879- `encode_cell / decode_cell` converts cell addresses.
880- `encode_range / decode_range` converts cell ranges.
881
882## Common Spreadsheet Format
883
884js-xlsx conforms to the Common Spreadsheet Format (CSF):
885
886### General Structures
887
888Cell address objects are stored as `{c:C, r:R}` where `C` and `R` are 0-indexed
889column and row numbers, respectively. For example, the cell address `B5` is
890represented by the object `{c:1, r:4}`.
891
892Cell range objects are stored as `{s:S, e:E}` where `S` is the first cell and
893`E` is the last cell in the range. The ranges are inclusive. For example, the
894range `A3:B7` is represented by the object `{s:{c:0, r:2}, e:{c:1, r:6}}`.
895Utility functions perform a row-major order walk traversal of a sheet range:
896
897```js
898for(var R = range.s.r; R <= range.e.r; ++R) {
899 for(var C = range.s.c; C <= range.e.c; ++C) {
900 var cell_address = {c:C, r:R};
901 /* if an A1-style address is needed, encode the address */
902 var cell_ref = XLSX.utils.encode_cell(cell_address);
903 }
904}
905```
906
907### Cell Object
908
909Cell objects are plain JS objects with keys and values following the convention:
910
911| Key | Description |
912| --- | ---------------------------------------------------------------------- |
913| `v` | raw value (see Data Types section for more info) |
914| `w` | formatted text (if applicable) |
915| `t` | type: `b` Boolean, `e` Error, `n` Number, `d` Date, `s` Text, `z` Stub |
916| `f` | cell formula encoded as an A1-style string (if applicable) |
917| `F` | range of enclosing array if formula is array formula (if applicable) |
918| `r` | rich text encoding (if applicable) |
919| `h` | HTML rendering of the rich text (if applicable) |
920| `c` | comments associated with the cell |
921| `z` | number format string associated with the cell (if requested) |
922| `l` | cell hyperlink object (`.Target` holds link, `.Tooltip` is tooltip) |
923| `s` | the style/theme of the cell (if applicable) |
924
925Built-in export utilities (such as the CSV exporter) will use the `w` text if it
926is available. To change a value, be sure to delete `cell.w` (or set it to
927`undefined`) before attempting to export. The utilities will regenerate the `w`
928text from the number format (`cell.z`) and the raw value if possible.
929
930The actual array formula is stored in the `f` field of the first cell in the
931array range. Other cells in the range will omit the `f` field.
932
933#### Data Types
934
935The raw value is stored in the `v` value property, interpreted based on the `t`
936type property. This separation allows for representation of numbers as well as
937numeric text. There are 6 valid cell types:
938
939| Type | Description |
940| :--: | :-------------------------------------------------------------------- |
941| `b` | Boolean: value interpreted as JS `boolean` |
942| `e` | Error: value is a numeric code and `w` property stores common name ** |
943| `n` | Number: value is a JS `number` ** |
944| `d` | Date: value is a JS `Date` object or string to be parsed as Date ** |
945| `s` | Text: value interpreted as JS `string` and written as text ** |
946| `z` | Stub: blank stub cell that is ignored by data processing utilities ** |
947
948<details>
949 <summary><b>Error values and interpretation</b> (click to show)</summary>
950
951| Value | Error Meaning |
952| -----: | :-------------- |
953| `0x00` | `#NULL!` |
954| `0x07` | `#DIV/0!` |
955| `0x0F` | `#VALUE!` |
956| `0x17` | `#REF!` |
957| `0x1D` | `#NAME?` |
958| `0x24` | `#NUM!` |
959| `0x2A` | `#N/A` |
960| `0x2B` | `#GETTING_DATA` |
961
962</details>
963
964Type `n` is the Number type. This includes all forms of data that Excel stores
965as numbers, such as dates/times and Boolean fields. Excel exclusively uses data
966that can be fit in an IEEE754 floating point number, just like JS Number, so the
967`v` field holds the raw number. The `w` field holds formatted text. Dates are
968stored as numbers by default and converted with `XLSX.SSF.parse_date_code`.
969
970Type `d` is the Date type, generated only when the option `cellDates` is passed.
971Since JSON does not have a natural Date type, parsers are generally expected to
972store ISO 8601 Date strings like you would get from `date.toISOString()`. On
973the other hand, writers and exporters should be able to handle date strings and
974JS Date objects. Note that Excel disregards timezone modifiers and treats all
975dates in the local timezone. The library does not correct for this error.
976
977Type `s` is the String type. Values are explicitly stored as text. Excel will
978interpret these cells as "number stored as text". Generated Excel files
979automatically suppress that class of error, but other formats may elicit errors.
980
981Type `z` represents blank stub cells. They are generated in cases where cells
982have no assigned value but hold comments or other metadata. They are ignored by
983the core library data processing utility functions. By default these cells are
984not generated; the parser `sheetStubs` option must be set to `true`.
985
986
987#### Dates
988
989<details>
990 <summary><b>Excel Date Code details</b> (click to show)</summary>
991
992By default, Excel stores dates as numbers with a format code that specifies date
993processing. For example, the date `19-Feb-17` is stored as the number `42785`
994with a number format of `d-mmm-yy`. The `SSF` module understands number formats
995and performs the appropriate conversion.
996
997XLSX also supports a special date type `d` where the data is an ISO 8601 date
998string. The formatter converts the date back to a number.
999
1000The default behavior for all parsers is to generate number cells. Setting
1001`cellDates` to true will force the generators to store dates.
1002
1003</details>
1004
1005<details>
1006 <summary><b>Time Zones and Dates</b> (click to show)</summary>
1007
1008Excel has no native concept of universal time. All times are specified in the
1009local time zone. Excel limitations prevent specifying true absolute dates.
1010
1011Following Excel, this library treats all dates as relative to local time zone.
1012
1013</details>
1014
1015<details>
1016 <summary><b>Epochs: 1900 and 1904</b> (click to show)</summary>
1017
1018Excel supports two epochs (January 1 1900 and January 1 1904), see
1019["1900 vs. 1904 Date System" article](http://support2.microsoft.com/kb/180162).
1020The workbook's epoch can be determined by examining the workbook's
1021`wb.Workbook.WBProps.date1904` property:
1022
1023```js
1024!!(((wb.Workbook||{}).WBProps||{}).date1904)
1025```
1026
1027</details>
1028
1029### Sheet Objects
1030
1031Each key that does not start with `!` maps to a cell (using `A-1` notation)
1032
1033`sheet[address]` returns the cell object for the specified address.
1034
1035**Special sheet keys (accessible as `sheet[key]`, each starting with `!`):**
1036
1037- `sheet['!ref']`: A-1 based range representing the sheet range. Functions that
1038 work with sheets should use this parameter to determine the range. Cells that
1039 are assigned outside of the range are not processed. In particular, when
1040 writing a sheet by hand, cells outside of the range are not included
1041
1042 Functions that handle sheets should test for the presence of `!ref` field.
1043 If the `!ref` is omitted or is not a valid range, functions are free to treat
1044 the sheet as empty or attempt to guess the range. The standard utilities that
1045 ship with this library treat sheets as empty (for example, the CSV output is
1046 empty string).
1047
1048 When reading a worksheet with the `sheetRows` property set, the ref parameter
1049 will use the restricted range. The original range is set at `ws['!fullref']`
1050
1051- `sheet['!margins']`: Object representing the page margins. The default values
1052 follow Excel's "normal" preset. Excel also has a "wide" and a "narrow" preset
1053 but they are stored as raw measurements. The main properties are listed below:
1054
1055<details>
1056 <summary><b>Page margin details</b> (click to show)</summary>
1057
1058| key | description | "normal" | "wide" | "narrow" |
1059|----------|------------------------|:---------|:-------|:-------- |
1060| `left` | left margin (inches) | `0.7` | `1.0` | `0.25` |
1061| `right` | right margin (inches) | `0.7` | `1.0` | `0.25` |
1062| `top` | top margin (inches) | `0.75` | `1.0` | `0.75` |
1063| `bottom` | bottom margin (inches) | `0.75` | `1.0` | `0.75` |
1064| `header` | header margin (inches) | `0.3` | `0.5` | `0.3` |
1065| `footer` | footer margin (inches) | `0.3` | `0.5` | `0.3` |
1066
1067```js
1068/* Set worksheet sheet to "normal" */
1069ws["!margins"]={left:0.7, right:0.7, top:0.75,bottom:0.75,header:0.3,footer:0.3}
1070/* Set worksheet sheet to "wide" */
1071ws["!margins"]={left:1.0, right:1.0, top:1.0, bottom:1.0, header:0.5,footer:0.5}
1072/* Set worksheet sheet to "narrow" */
1073ws["!margins"]={left:0.25,right:0.25,top:0.75,bottom:0.75,header:0.3,footer:0.3}
1074```
1075</details>
1076
1077#### Worksheet Object
1078
1079In addition to the base sheet keys, worksheets also add:
1080
1081- `ws['!cols']`: array of column properties objects. Column widths are actually
1082 stored in files in a normalized manner, measured in terms of the "Maximum
1083 Digit Width" (the largest width of the rendered digits 0-9, in pixels). When
1084 parsed, the column objects store the pixel width in the `wpx` field, character
1085 width in the `wch` field, and the maximum digit width in the `MDW` field.
1086
1087- `ws['!rows']`: array of row properties objects as explained later in the docs.
1088 Each row object encodes properties including row height and visibility.
1089
1090- `ws['!merges']`: array of range objects corresponding to the merged cells in
1091 the worksheet. Plain text formats do not support merge cells. CSV export
1092 will write all cells in the merge range if they exist, so be sure that only
1093 the first cell (upper-left) in the range is set.
1094
1095- `ws['!protect']`: object of write sheet protection properties. The `password`
1096 key specifies the password for formats that support password-protected sheets
1097 (XLSX/XLSB/XLS). The writer uses the XOR obfuscation method. The following
1098 keys control the sheet protection -- set to `false` to enable a feature when
1099 sheet is locked or set to `true` to disable a feature:
1100
1101<details>
1102 <summary><b>Worksheet Protection Details</b> (click to show)</summary>
1103
1104| key | feature (true=disabled / false=enabled) | default |
1105|:----------------------|:----------------------------------------|:-----------|
1106| `selectLockedCells` | Select locked cells | enabled |
1107| `selectUnlockedCells` | Select unlocked cells | enabled |
1108| `formatCells` | Format cells | disabled |
1109| `formatColumns` | Format columns | disabled |
1110| `formatRows` | Format rows | disabled |
1111| `insertColumns` | Insert columns | disabled |
1112| `insertRows` | Insert rows | disabled |
1113| `insertHyperlinks` | Insert hyperlinks | disabled |
1114| `deleteColumns` | Delete columns | disabled |
1115| `deleteRows` | Delete rows | disabled |
1116| `sort` | Sort | disabled |
1117| `autoFilter` | Filter | disabled |
1118| `pivotTables` | Use PivotTable reports | disabled |
1119| `objects` | Edit objects | enabled |
1120| `scenarios` | Edit scenarios | enabled |
1121</details>
1122
1123- `ws['!autofilter']`: AutoFilter object following the schema:
1124
1125```typescript
1126type AutoFilter = {
1127 ref:string; // A-1 based range representing the AutoFilter table range
1128}
1129```
1130
1131#### Chartsheet Object
1132
1133Chartsheets are represented as standard sheets. They are distinguished with the
1134`!type` property set to `"chart"`.
1135
1136The underlying data and `!ref` refer to the cached data in the chartsheet. The
1137first row of the chartsheet is the underlying header.
1138
1139#### Macrosheet Object
1140
1141Macrosheets are represented as standard sheets. They are distinguished with the
1142`!type` property set to `"macro"`.
1143
1144#### Dialogsheet Object
1145
1146Dialogsheets are represented as standard sheets. They are distinguished with the
1147`!type` property set to `"dialog"`.
1148
1149### Workbook Object
1150
1151`workbook.SheetNames` is an ordered list of the sheets in the workbook
1152
1153`wb.Sheets[sheetname]` returns an object representing the worksheet.
1154
1155`wb.Props` is an object storing the standard properties. `wb.Custprops` stores
1156custom properties. Since the XLS standard properties deviate from the XLSX
1157standard, XLS parsing stores core properties in both places.
1158
1159`wb.Workbook` stores [workbook-level attributes](#workbook-level-attributes).
1160
1161#### Workbook File Properties
1162
1163The various file formats use different internal names for file properties. The
1164workbook `Props` object normalizes the names:
1165
1166<details>
1167 <summary><b>File Properties</b> (click to show)</summary>
1168
1169| JS Name | Excel Description |
1170|:--------------|:-------------------------------|
1171| `Title` | Summary tab "Title" |
1172| `Subject` | Summary tab "Subject" |
1173| `Author` | Summary tab "Author" |
1174| `Manager` | Summary tab "Manager" |
1175| `Company` | Summary tab "Company" |
1176| `Category` | Summary tab "Category" |
1177| `Keywords` | Summary tab "Keywords" |
1178| `Comments` | Summary tab "Comments" |
1179| `LastAuthor` | Statistics tab "Last saved by" |
1180| `CreatedDate` | Statistics tab "Created" |
1181
1182</details>
1183
1184For example, to set the workbook title property:
1185
1186```js
1187if(!wb.Props) wb.Props = {};
1188wb.Props.Title = "Insert Title Here";
1189```
1190
1191Custom properties are added in the workbook `Custprops` object:
1192
1193```js
1194if(!wb.Custprops) wb.Custprops = {};
1195wb.Custprops["Custom Property"] = "Custom Value";
1196```
1197
1198Writers will process the `Props` key of the options object:
1199
1200```js
1201/* force the Author to be "SheetJS" */
1202XLSX.write(wb, {Props:{Author:"SheetJS"}});
1203```
1204
1205### Workbook-Level Attributes
1206
1207`wb.Workbook` stores workbook-level attributes.
1208
1209#### Defined Names
1210
1211`wb.Workbook.Names` is an array of defined name objects which have the keys:
1212
1213<details>
1214 <summary><b>Defined Name Properties</b> (click to show)</summary>
1215
1216| Key | Description |
1217|:----------|:-----------------------------------------------------------------|
1218| `Sheet` | Name scope. Sheet Index (0 = first sheet) or `null` (Workbook) |
1219| `Name` | Case-sensitive name. Standard rules apply ** |
1220| `Ref` | A1-style Reference (`"Sheet1!$A$1:$D$20"`) |
1221| `Comment` | Comment (only applicable for XLS/XLSX/XLSB) |
1222
1223</details>
1224
1225Excel allows two sheet-scoped defined names to share the same name. However, a
1226sheet-scoped name cannot collide with a workbook-scope name. Workbook writers
1227may not enforce this constraint.
1228
1229#### Workbook Views
1230
1231`wb.Workbook.Views` is an array of workbook view objects which have the keys:
1232
1233| Key | Description |
1234|:----------------|:----------------------------------------------------|
1235| `RTL` | If true, display right-to-left |
1236
1237#### Miscellaneous Workbook Properties
1238
1239`wb.Workbook.WBProps` holds other workbook properties:
1240
1241| Key | Description |
1242|:----------------|:----------------------------------------------------|
1243| `CodeName` | [VBA Project Workbook Code Name](#vba-and-macros) |
1244| `date1904` | epoch: 0/false for 1900 system, 1/true for 1904 |
1245| `filterPrivacy` | Warn or strip personally identifying info on save |
1246
1247### Document Features
1248
1249Even for basic features like date storage, the official Excel formats store the
1250same content in different ways. The parsers are expected to convert from the
1251underlying file format representation to the Common Spreadsheet Format. Writers
1252are expected to convert from CSF back to the underlying file format.
1253
1254#### Formulae
1255
1256The A1-style formula string is stored in the `f` field. Even though different
1257file formats store the formulae in different ways, the formats are translated.
1258Even though some formats store formulae with a leading equal sign, CSF formulae
1259do not start with `=`.
1260
1261<details>
1262 <summary><b>Representation of A1=1, A2=2, A3=A1+A2</b> (click to show)</summary>
1263
1264```js
1265{
1266 "!ref": "A1:A3",
1267 A1: { t:'n', v:1 },
1268 A2: { t:'n', v:2 },
1269 A3: { t:'n', v:3, f:'A1+A2' }
1270}
1271```
1272</details>
1273
1274Shared formulae are decompressed and each cell has the formula corresponding to
1275its cell. Writers generally do not attempt to generate shared formulae.
1276
1277Cells with formula entries but no value will be serialized in a way that Excel
1278and other spreadsheet tools will recognize. This library will not automatically
1279compute formula results! For example, to compute `BESSELJ` in a worksheet:
1280
1281<details>
1282 <summary><b>Formula without known value</b> (click to show)</summary>
1283
1284```js
1285{
1286 "!ref": "A1:A3",
1287 A1: { t:'n', v:3.14159 },
1288 A2: { t:'n', v:2 },
1289 A3: { t:'n', f:'BESSELJ(A1,A2)' }
1290}
1291```
1292</details>
1293
1294**Array Formulae**
1295
1296Array formulae are stored in the top-left cell of the array block. All cells
1297of an array formula have a `F` field corresponding to the range. A single-cell
1298formula can be distinguished from a plain formula by the presence of `F` field.
1299
1300<details>
1301 <summary><b>Array Formula examples</b> (click to show)</summary>
1302
1303For example, setting the cell `C1` to the array formula `{=SUM(A1:A3*B1:B3)}`:
1304
1305```js
1306worksheet['C1'] = { t:'n', f: "SUM(A1:A3*B1:B3)", F:"C1:C1" };
1307```
1308
1309For a multi-cell array formula, every cell has the same array range but only the
1310first cell specifies the formula. Consider `D1:D3=A1:A3*B1:B3`:
1311
1312```js
1313worksheet['D1'] = { t:'n', F:"D1:D3", f:"A1:A3*B1:B3" };
1314worksheet['D2'] = { t:'n', F:"D1:D3" };
1315worksheet['D3'] = { t:'n', F:"D1:D3" };
1316```
1317
1318</details>
1319
1320Utilities and writers are expected to check for the presence of a `F` field and
1321ignore any possible formula element `f` in cells other than the starting cell.
1322They are not expected to perform validation of the formulae!
1323
1324<details>
1325 <summary><b>Formula Output Utility Function</b> (click to show)</summary>
1326
1327The `sheet_to_formulae` method generates one line per formula or array formula.
1328Array formulae are rendered in the form `range=formula` while plain cells are
1329rendered in the form `cell=formula or value`. Note that string literals are
1330prefixed with an apostrophe `'`, consistent with Excel's formula bar display.
1331</details>
1332
1333<details>
1334 <summary><b>Formulae File Format Details</b> (click to show)</summary>
1335
1336| Storage Representation | Formats | Read | Write |
1337|:-----------------------|:-------------------------|:-----:|:-----:|
1338| A1-style strings | XLSX | :o: | :o: |
1339| RC-style strings | XLML and plain text | :o: | :o: |
1340| BIFF Parsed formulae | XLSB and all XLS formats | :o: | |
1341| OpenFormula formulae | ODS/FODS/UOS | :o: | :o: |
1342
1343Since Excel prohibits named cells from colliding with names of A1 or RC style
1344cell references, a (not-so-simple) regex conversion is possible. BIFF Parsed
1345formulae have to be explicitly unwound. OpenFormula formulae can be converted
1346with regular expressions.
1347</details>
1348
1349#### Column Properties
1350
1351The `!cols` array in each worksheet, if present, is a collection of `ColInfo`
1352objects which have the following properties:
1353
1354```typescript
1355type ColInfo = {
1356 /* visibility */
1357 hidden?: boolean; // if true, the column is hidden
1358
1359 /* column width is specified in one of the following ways: */
1360 wpx?: number; // width in screen pixels
1361 width?: number; // width in Excel's "Max Digit Width", width*256 is integral
1362 wch?: number; // width in characters
1363
1364 /* other fields for preserving features from files */
1365 MDW?: number; // Excel's "Max Digit Width" unit, always integral
1366};
1367```
1368
1369<details>
1370 <summary><b>Why are there three width types?</b> (click to show)</summary>
1371
1372There are three different width types corresponding to the three different ways
1373spreadsheets store column widths:
1374
1375SYLK and other plain text formats use raw character count. Contemporaneous tools
1376like Visicalc and Multiplan were character based. Since the characters had the
1377same width, it sufficed to store a count. This tradition was continued into the
1378BIFF formats.
1379
1380SpreadsheetML (2003) tried to align with HTML by standardizing on screen pixel
1381count throughout the file. Column widths, row heights, and other measures use
1382pixels. When the pixel and character counts do not align, Excel rounds values.
1383
1384XLSX internally stores column widths in a nebulous "Max Digit Width" form. The
1385Max Digit Width is the width of the largest digit when rendered (generally the
1386"0" character is the widest). The internal width must be an integer multiple of
1387the the width divided by 256. ECMA-376 describes a formula for converting
1388between pixels and the internal width. This represents a hybrid approach.
1389
1390Read functions attempt to populate all three properties. Write functions will
1391try to cycle specified values to the desired type. In order to avoid potential
1392conflicts, manipulation should delete the other properties first. For example,
1393when changing the pixel width, delete the `wch` and `width` properties.
1394</details>
1395
1396<details>
1397 <summary><b>Implementation details</b> (click to show)</summary>
1398
1399Given the constraints, it is possible to determine the MDW without actually
1400inspecting the font! The parsers guess the pixel width by converting from width
1401to pixels and back, repeating for all possible MDW and selecting the MDW that
1402minimizes the error. XLML actually stores the pixel width, so the guess works
1403in the opposite direction.
1404
1405Even though all of the information is made available, writers are expected to
1406follow the priority order:
1407
14081) use `width` field if available
14092) use `wpx` pixel width if available
14103) use `wch` character count if available
1411</details>
1412
1413#### Row Properties
1414
1415The `!rows` array in each worksheet, if present, is a collection of `RowInfo`
1416objects which have the following properties:
1417
1418```typescript
1419type RowInfo = {
1420 /* visibility */
1421 hidden?: boolean; // if true, the row is hidden
1422
1423 /* row height is specified in one of the following ways: */
1424 hpx?: number; // height in screen pixels
1425 hpt?: number; // height in points
1426
1427 level?: number; // 0-indexed outline / group level
1428};
1429```
1430
1431Note: Excel UI displays the base outline level as `1` and the max level as `8`.
1432The `level` field stores the base outline as `0` and the max level as `7`.
1433
1434<details>
1435 <summary><b>Implementation details</b> (click to show)</summary>
1436
1437Excel internally stores row heights in points. The default resolution is 72 DPI
1438or 96 PPI, so the pixel and point size should agree. For different resolutions
1439they may not agree, so the library separates the concepts.
1440
1441Even though all of the information is made available, writers are expected to
1442follow the priority order:
1443
14441) use `hpx` pixel height if available
14452) use `hpt` point height if available
1446</details>
1447
1448#### Number Formats
1449
1450The `cell.w` formatted text for each cell is produced from `cell.v` and `cell.z`
1451format. If the format is not specified, the Excel `General` format is used.
1452The format can either be specified as a string or as an index into the format
1453table. Parsers are expected to populate `workbook.SSF` with the number format
1454table. Writers are expected to serialize the table.
1455
1456Custom tools should ensure that the local table has each used format string
1457somewhere in the table. Excel convention mandates that the custom formats start
1458at index 164. The following example creates a custom format from scratch:
1459
1460<details>
1461 <summary><b>New worksheet with custom format</b> (click to show)</summary>
1462
1463```js
1464var wb = {
1465 SheetNames: ["Sheet1"],
1466 Sheets: {
1467 Sheet1: {
1468 "!ref":"A1:C1",
1469 A1: { t:"n", v:10000 }, // <-- General format
1470 B1: { t:"n", v:10000, z: "0%" }, // <-- Builtin format
1471 C1: { t:"n", v:10000, z: "\"T\"\ #0.00" } // <-- Custom format
1472 }
1473 }
1474}
1475```
1476</details>
1477
1478The rules are slightly different from how Excel displays custom number formats.
1479In particular, literal characters must be wrapped in double quotes or preceded
1480by a backslash. For more info, see the Excel documentation article
1481`Create or delete a custom number format` or ECMA-376 18.8.31 (Number Formats)
1482
1483
1484<details>
1485 <summary><b>Default Number Formats</b> (click to show)</summary>
1486
1487The default formats are listed in ECMA-376 18.8.30:
1488
1489| ID | Format |
1490|---:|:---------------------------|
1491| 0 | `General` |
1492| 1 | `0` |
1493| 2 | `0.00` |
1494| 3 | `#,##0` |
1495| 4 | `#,##0.00` |
1496| 9 | `0%` |
1497| 10 | `0.00%` |
1498| 11 | `0.00E+00` |
1499| 12 | `# ?/?` |
1500| 13 | `# ??/??` |
1501| 14 | `m/d/yy` (see below) |
1502| 15 | `d-mmm-yy` |
1503| 16 | `d-mmm` |
1504| 17 | `mmm-yy` |
1505| 18 | `h:mm AM/PM` |
1506| 19 | `h:mm:ss AM/PM` |
1507| 20 | `h:mm` |
1508| 21 | `h:mm:ss` |
1509| 22 | `m/d/yy h:mm` |
1510| 37 | `#,##0 ;(#,##0)` |
1511| 38 | `#,##0 ;[Red](#,##0)` |
1512| 39 | `#,##0.00;(#,##0.00)` |
1513| 40 | `#,##0.00;[Red](#,##0.00)` |
1514| 45 | `mm:ss` |
1515| 46 | `[h]:mm:ss` |
1516| 47 | `mmss.0` |
1517| 48 | `##0.0E+0` |
1518| 49 | `@` |
1519
1520</details>
1521
1522Format 14 (`m/d/yy`) is localized by Excel: even though the file specifies that
1523number format, it will be drawn differently based on system settings. It makes
1524sense when the producer and consumer of files are in the same locale, but that
1525is not always the case over the Internet. To get around this ambiguity, parse
1526functions accept the `dateNF` option to override the interpretation of that
1527specific format string.
1528
1529#### Hyperlinks
1530
1531Hyperlinks are stored in the `l` key of cell objects. The `Target` field of the
1532hyperlink object is the target of the link, including the URI fragment. Tooltips
1533are stored in the `Tooltip` field and are displayed when you move your mouse
1534over the text.
1535
1536For example, the following snippet creates a link from cell `A3` to
1537<http://sheetjs.com> with the tip `"Find us @ SheetJS.com!"`:
1538
1539```js
1540ws['A3'].l = { Target:"http://sheetjs.com", Tooltip:"Find us @ SheetJS.com!" };
1541```
1542
1543Note that Excel does not automatically style hyperlinks -- they will generally
1544be displayed as normal text.
1545
1546Links where the target is a cell or range or defined name in the same workbook
1547("Internal Links") are marked with a leading hash character:
1548
1549```js
1550ws['A2'].l = { Target:"#E2" }; /* link to cell E2 */
1551```
1552
1553#### Cell Comments
1554
1555Cell comments are objects stored in the `c` array of cell objects. The actual
1556contents of the comment are split into blocks based on the comment author. The
1557`a` field of each comment object is the author of the comment and the `t` field
1558is the plain text representation.
1559
1560For example, the following snippet appends a cell comment into cell `A1`:
1561
1562```js
1563if(!ws.A1.c) ws.A1.c = [];
1564ws.A1.c.push({a:"SheetJS", t:"I'm a little comment, short and stout!"});
1565```
1566
1567Note: XLSB enforces a 54 character limit on the Author name. Names longer than
156854 characters may cause issues with other formats.
1569
1570To mark a comment as normally hidden, set the `hidden` property:
1571
1572```js
1573if(!ws.A1.c) ws.A1.c = [];
1574ws.A1.c.push({a:"SheetJS", t:"This comment is visible"});
1575
1576if(!ws.A2.c) ws.A2.c = [];
1577ws.A2.c.hidden = true;
1578ws.A2.c.push({a:"SheetJS", t:"This comment will be hidden"});
1579```
1580
1581#### Sheet Visibility
1582
1583Excel enables hiding sheets in the lower tab bar. The sheet data is stored in
1584the file but the UI does not readily make it available. Standard hidden sheets
1585are revealed in the "Unhide" menu. Excel also has "very hidden" sheets which
1586cannot be revealed in the menu. It is only accessible in the VB Editor!
1587
1588The visibility setting is stored in the `Hidden` property of sheet props array.
1589
1590<details>
1591 <summary><b>More details</b> (click to show)</summary>
1592
1593| Value | Definition |
1594|:-----:|:------------|
1595| 0 | Visible |
1596| 1 | Hidden |
1597| 2 | Very Hidden |
1598
1599With <https://rawgit.com/SheetJS/test_files/master/sheet_visibility.xlsx>:
1600
1601```js
1602> wb.Workbook.Sheets.map(function(x) { return [x.name, x.Hidden] })
1603[ [ 'Visible', 0 ], [ 'Hidden', 1 ], [ 'VeryHidden', 2 ] ]
1604```
1605
1606Non-Excel formats do not support the Very Hidden state. The best way to test
1607if a sheet is visible is to check if the `Hidden` property is logical truth:
1608
1609```js
1610> wb.Workbook.Sheets.map(function(x) { return [x.name, !x.Hidden] })
1611[ [ 'Visible', true ], [ 'Hidden', false ], [ 'VeryHidden', false ] ]
1612```
1613</details>
1614
1615#### VBA and Macros
1616
1617VBA Macros are stored in a special data blob that is exposed in the `vbaraw`
1618property of the workbook object when the `bookVBA` option is `true`. They are
1619supported in `XLSM`, `XLSB`, and `BIFF8 XLS` formats. The supported format
1620writers automatically insert the data blobs if it is present in the workbook and
1621associate with the worksheet names.
1622
1623<details>
1624 <summary><b>Custom Code Names</b> (click to show)</summary>
1625
1626The workbook code name is stored in `wb.Workbook.WBProps.CodeName`. By default,
1627Excel will write `ThisWorkbook` or a translated phrase like `DieseArbeitsmappe`.
1628Worksheet and Chartsheet code names are in the worksheet properties object at
1629`wb.Workbook.Sheets[i].CodeName`. Macrosheets and Dialogsheets are ignored.
1630
1631The readers and writers preserve the code names, but they have to be manually
1632set when adding a VBA blob to a different workbook.
1633
1634</details>
1635
1636<details>
1637 <summary><b>Macrosheets</b> (click to show)</summary>
1638
1639Older versions of Excel also supported a non-VBA "macrosheet" sheet type that
1640stored automation commands. These are exposed in objects with the `!type`
1641property set to `"macro"`.
1642
1643</details>
1644
1645<details>
1646 <summary><b>Detecting macros in workbooks</b> (click to show)</summary>
1647
1648The `vbaraw` field will only be set if macros are present, so testing is simple:
1649
1650```js
1651function wb_has_macro(wb/*:workbook*/)/*:boolean*/ {
1652 if(!!wb.vbaraw) return true;
1653 const sheets = wb.SheetNames.map((n) => wb.Sheets[n]);
1654 return sheets.some((ws) => !!ws && ws['!type']=='macro');
1655}
1656```
1657
1658</details>
1659
1660## Parsing Options
1661
1662The exported `read` and `readFile` functions accept an options argument:
1663
1664| Option Name | Default | Description |
1665| :---------- | ------: | :--------------------------------------------------- |
1666|`type` | | Input data encoding (see Input Type below) |
1667|`raw` | false | If true, plain text parsing will not parse values ** |
1668|`codepage` | | If specified, use code page when appropriate ** |
1669|`cellFormula`| true | Save formulae to the .f field |
1670|`cellHTML` | true | Parse rich text and save HTML to the `.h` field |
1671|`cellNF` | false | Save number format string to the `.z` field |
1672|`cellStyles` | false | Save style/theme info to the `.s` field |
1673|`cellText` | true | Generated formatted text to the `.w` field |
1674|`cellDates` | false | Store dates as type `d` (default is `n`) |
1675|`dateNF` | | If specified, use the string for date code 14 ** |
1676|`sheetStubs` | false | Create cell objects of type `z` for stub cells |
1677|`sheetRows` | 0 | If >0, read the first `sheetRows` rows ** |
1678|`bookDeps` | false | If true, parse calculation chains |
1679|`bookFiles` | false | If true, add raw files to book object ** |
1680|`bookProps` | false | If true, only parse enough to get book metadata ** |
1681|`bookSheets` | false | If true, only parse enough to get the sheet names |
1682|`bookVBA` | false | If true, copy VBA blob to `vbaraw` field ** |
1683|`password` | "" | If defined and file is encrypted, use password ** |
1684|`WTF` | false | If true, throw errors on unexpected file features ** |
1685
1686- Even if `cellNF` is false, formatted text will be generated and saved to `.w`
1687- In some cases, sheets may be parsed even if `bookSheets` is false.
1688- Excel aggressively tries to interpret values from CSV and other plain text.
1689 This leads to surprising behavior! The `raw` option suppresses value parsing.
1690- `bookSheets` and `bookProps` combine to give both sets of information
1691- `Deps` will be an empty object if `bookDeps` is false
1692- `bookFiles` behavior depends on file type:
1693 * `keys` array (paths in the ZIP) for ZIP-based formats
1694 * `files` hash (mapping paths to objects representing the files) for ZIP
1695 * `cfb` object for formats using CFB containers
1696- `sheetRows-1` rows will be generated when looking at the JSON object output
1697 (since the header row is counted as a row when parsing the data)
1698- `bookVBA` merely exposes the raw VBA CFB object. It does not parse the data.
1699 XLSM and XLSB store the VBA CFB object in `xl/vbaProject.bin`. BIFF8 XLS mixes
1700 the VBA entries alongside the core Workbook entry, so the library generates a
1701 new XLSB-compatible blob from the XLS CFB container.
1702- `codepage` is applied to BIFF2 - BIFF5 files without `CodePage` records and to
1703 CSV files without BOM in `type:"binary"`. BIFF8 XLS always defaults to 1200.
1704- Currently only XOR encryption is supported. Unsupported error will be thrown
1705 for files employing other encryption methods.
1706- WTF is mainly for development. By default, the parser will suppress read
1707 errors on single worksheets, allowing you to read from the worksheets that do
1708 parse properly. Setting `WTF:1` forces those errors to be thrown.
1709
1710### Input Type
1711
1712Strings can be interpreted in multiple ways. The `type` parameter for `read`
1713tells the library how to parse the data argument:
1714
1715| `type` | expected input |
1716|------------|-----------------------------------------------------------------|
1717| `"base64"` | string: Base64 encoding of the file |
1718| `"binary"` | string: binary string (byte `n` is `data.charCodeAt(n)`) |
1719| `"string"` | string: JS string (characters interpreted as UTF8) |
1720| `"buffer"` | nodejs Buffer |
1721| `"array"` | array: array of 8-bit unsigned int (byte `n` is `data[n]`) |
1722| `"file"` | string: path of file that will be read (nodejs only) |
1723
1724### Guessing File Type
1725
1726<details>
1727 <summary><b>Implementation Details</b> (click to show)</summary>
1728
1729Excel and other spreadsheet tools read the first few bytes and apply other
1730heuristics to determine a file type. This enables file type punning: renaming
1731files with the `.xls` extension will tell your computer to use Excel to open the
1732file but Excel will know how to handle it. This library applies similar logic:
1733
1734| Byte 0 | Raw File Type | Spreadsheet Types |
1735|:-------|:--------------|:----------------------------------------------------|
1736| `0xD0` | CFB Container | BIFF 5/8 or password-protected XLSX/XLSB or WQ3/QPW |
1737| `0x09` | BIFF Stream | BIFF 2/3/4/5 |
1738| `0x3C` | XML/HTML | SpreadsheetML / Flat ODS / UOS1 / HTML / plain text |
1739| `0x50` | ZIP Archive | XLSB or XLSX/M or ODS or UOS2 or plain text |
1740| `0x49` | Plain Text | SYLK or plain text |
1741| `0x54` | Plain Text | DIF or plain text |
1742| `0xEF` | UTF8 Encoded | SpreadsheetML / Flat ODS / UOS1 / HTML / plain text |
1743| `0xFF` | UTF16 Encoded | SpreadsheetML / Flat ODS / UOS1 / HTML / plain text |
1744| `0x00` | Record Stream | Lotus WK\* or Quattro Pro or plain text |
1745| `0x7B` | Plain text | RTF or plain text |
1746| `0x0A` | Plain text | SpreadsheetML / Flat ODS / UOS1 / HTML / plain text |
1747| `0x0D` | Plain text | SpreadsheetML / Flat ODS / UOS1 / HTML / plain text |
1748| `0x20` | Plain text | SpreadsheetML / Flat ODS / UOS1 / HTML / plain text |
1749
1750DBF files are detected based on the first byte as well as the third and fourth
1751bytes (corresponding to month and day of the file date)
1752
1753Plain text format guessing follows the priority order:
1754
1755| Format | Test |
1756|:-------|:--------------------------------------------------------------------|
1757| XML | `<?xml` appears in the first 1024 characters |
1758| HTML | starts with `<` and HTML tags appear in the first 1024 characters * |
1759| XML | starts with `<` |
1760| RTF | starts with `{\rt` |
1761| DSV | starts with `/sep=.$/`, separator is the specified character |
1762| DSV | more unquoted `";"` chars than `"\t"` or `","` in the first 1024 |
1763| TSV | more unquoted `"\t"` chars than `","` chars in the first 1024 |
1764| CSV | one of the first 1024 characters is a comma `","` |
1765| ETH | starts with `socialcalc:version:` |
1766| PRN | (default) |
1767
1768- HTML tags include: `html`, `table`, `head`, `meta`, `script`, `style`, `div`
1769
1770</details>
1771
1772<details>
1773 <summary><b>Why are random text files valid?</b> (click to show)</summary>
1774
1775Excel is extremely aggressive in reading files. Adding an XLS extension to any
1776display text file (where the only characters are ANSI display chars) tricks
1777Excel into thinking that the file is potentially a CSV or TSV file, even if it
1778is only one column! This library attempts to replicate that behavior.
1779
1780The best approach is to validate the desired worksheet and ensure it has the
1781expected number of rows or columns. Extracting the range is extremely simple:
1782
1783```js
1784var range = XLSX.utils.decode_range(worksheet['!ref']);
1785var ncols = range.e.c - range.s.c + 1, nrows = range.e.r - range.s.r + 1;
1786```
1787
1788</details>
1789
1790## Writing Options
1791
1792The exported `write` and `writeFile` functions accept an options argument:
1793
1794| Option Name | Default | Description |
1795| :---------- | -------: | :-------------------------------------------------- |
1796|`type` | | Output data encoding (see Output Type below) |
1797|`cellDates` | `false` | Store dates as type `d` (default is `n`) |
1798|`bookSST` | `false` | Generate Shared String Table ** |
1799|`bookType` | `"xlsx"` | Type of Workbook (see below for supported formats) |
1800|`sheet` | `""` | Name of Worksheet for single-sheet formats ** |
1801|`compression`| `false` | Use ZIP compression for ZIP-based formats ** |
1802|`Props` | | Override workbook properties when writing ** |
1803|`themeXLSX` | | Override theme XML when writing XLSX/XLSB/XLSM ** |
1804|`ignoreEC` | `true` | Suppress "number as text" errors ** |
1805
1806- `bookSST` is slower and more memory intensive, but has better compatibility
1807 with older versions of iOS Numbers
1808- The raw data is the only thing guaranteed to be saved. Features not described
1809 in this README may not be serialized.
1810- `cellDates` only applies to XLSX output and is not guaranteed to work with
1811 third-party readers. Excel itself does not usually write cells with type `d`
1812 so non-Excel tools may ignore the data or error in the presence of dates.
1813- `Props` is an object mirroring the workbook `Props` field. See the table from
1814 the [Workbook File Properties](#workbook-file-properties) section.
1815- if specified, the string from `themeXLSX` will be saved as the primary theme
1816 for XLSX/XLSB/XLSM files (to `xl/theme/theme1.xml` in the ZIP)
1817- Due to a bug in the program, some features like "Text to Columns" will crash
1818 Excel on worksheets where error conditions are ignored. The writer will mark
1819 files to ignore the error by default. Set `ignoreEC` to `false` to suppress.
1820
1821### Supported Output Formats
1822
1823For broad compatibility with third-party tools, this library supports many
1824output formats. The specific file type is controlled with `bookType` option:
1825
1826| `bookType` | file ext | container | sheets | Description |
1827| :--------- | -------: | :-------: | :----- |:------------------------------- |
1828| `xlsx` | `.xlsx` | ZIP | multi | Excel 2007+ XML Format |
1829| `xlsm` | `.xlsm` | ZIP | multi | Excel 2007+ Macro XML Format |
1830| `xlsb` | `.xlsb` | ZIP | multi | Excel 2007+ Binary Format |
1831| `biff8` | `.xls` | CFB | multi | Excel 97-2004 Workbook Format |
1832| `biff5` | `.xls` | CFB | multi | Excel 5.0/95 Workbook Format |
1833| `biff2` | `.xls` | none | single | Excel 2.0 Worksheet Format |
1834| `xlml` | `.xls` | none | multi | Excel 2003-2004 (SpreadsheetML) |
1835| `ods` | `.ods` | ZIP | multi | OpenDocument Spreadsheet |
1836| `fods` | `.fods` | none | multi | Flat OpenDocument Spreadsheet |
1837| `csv` | `.csv` | none | single | Comma Separated Values |
1838| `txt` | `.txt` | none | single | UTF-16 Unicode Text (TXT) |
1839| `sylk` | `.sylk` | none | single | Symbolic Link (SYLK) |
1840| `html` | `.html` | none | single | HTML Document |
1841| `dif` | `.dif` | none | single | Data Interchange Format (DIF) |
1842| `dbf` | `.dbf` | none | single | dBASE II + VFP Extensions (DBF) |
1843| `rtf` | `.rtf` | none | single | Rich Text Format (RTF) |
1844| `prn` | `.prn` | none | single | Lotus Formatted Text |
1845| `eth` | `.eth` | none | single | Ethercalc Record Format (ETH) |
1846
1847- `compression` only applies to formats with ZIP containers.
1848- Formats that only support a single sheet require a `sheet` option specifying
1849 the worksheet. If the string is empty, the first worksheet is used.
1850- `writeFile` will automatically guess the output file format based on the file
1851 extension if `bookType` is not specified. It will choose the first format in
1852 the aforementioned table that matches the extension.
1853
1854### Output Type
1855
1856The `type` argument for `write` mirrors the `type` argument for `read`:
1857
1858| `type` | output |
1859|------------|-----------------------------------------------------------------|
1860| `"base64"` | string: Base64 encoding of the file |
1861| `"binary"` | string: binary string (byte `n` is `data.charCodeAt(n)`) |
1862| `"string"` | string: JS string (characters interpreted as UTF8) |
1863| `"buffer"` | nodejs Buffer |
1864| `"array"` | ArrayBuffer, fallback array of 8-bit unsigned int |
1865| `"file"` | string: path of file that will be created (nodejs only) |
1866
1867## Utility Functions
1868
1869The `sheet_to_*` functions accept a worksheet and an optional options object.
1870
1871The `*_to_sheet` functions accept a data object and an optional options object.
1872
1873The examples are based on the following worksheet:
1874
1875```
1876XXX| A | B | C | D | E | F | G |
1877---+---+---+---+---+---+---+---+
1878 1 | S | h | e | e | t | J | S |
1879 2 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
1880 3 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
1881```
1882
1883### Array of Arrays Input
1884
1885`XLSX.utils.aoa_to_sheet` takes an array of arrays of JS values and returns a
1886worksheet resembling the input data. Numbers, Booleans and Strings are stored
1887as the corresponding styles. Dates are stored as date or numbers. Array holes
1888and explicit `undefined` values are skipped. `null` values may be stubbed. All
1889other values are stored as strings. The function takes an options argument:
1890
1891| Option Name | Default | Description |
1892| :---------- | :------: | :-------------------------------------------------- |
1893|`dateNF` | FMT 14 | Use specified date format in string output |
1894|`cellDates` | false | Store dates as type `d` (default is `n`) |
1895|`sheetStubs` | false | Create cell objects of type `z` for `null` values |
1896
1897<details>
1898 <summary><b>Examples</b> (click to show)</summary>
1899
1900To generate the example sheet:
1901
1902```js
1903var ws = XLSX.utils.aoa_to_sheet([
1904 "SheetJS".split(""),
1905 [1,2,3,4,5,6,7],
1906 [2,3,4,5,6,7,8]
1907]);
1908```
1909</details>
1910
1911`XLSX.utils.sheet_add_aoa` takes an array of arrays of JS values and updates an
1912existing worksheet object. It follows the same process as `aoa_to_sheet` and
1913accepts an options argument:
1914
1915| Option Name | Default | Description |
1916| :---------- | :------: | :-------------------------------------------------- |
1917|`dateNF` | FMT 14 | Use specified date format in string output |
1918|`cellDates` | false | Store dates as type `d` (default is `n`) |
1919|`sheetStubs` | false | Create cell objects of type `z` for `null` values |
1920|`origin` | | Use specified cell as starting point (see below) |
1921
1922`origin` is expected to be one of:
1923
1924| `origin` | Description |
1925| :--------------- | :-------------------------------------------------------- |
1926| (cell object) | Use specified cell (cell object) |
1927| (string) | Use specified cell (A1-style cell) |
1928| (number >= 0) | Start from the first column at specified row (0-indexed) |
1929| -1 | Append to bottom of worksheet starting on first column |
1930| (default) | Start from cell A1 |
1931
1932
1933<details>
1934 <summary><b>Examples</b> (click to show)</summary>
1935
1936Consider the worksheet:
1937
1938```
1939XXX| A | B | C | D | E | F | G |
1940---+---+---+---+---+---+---+---+
1941 1 | S | h | e | e | t | J | S |
1942 2 | 1 | 2 | | | 5 | 6 | 7 |
1943 3 | 2 | 3 | | | 6 | 7 | 8 |
1944 4 | 3 | 4 | | | 7 | 8 | 9 |
1945 5 | 4 | 5 | 6 | 7 | 8 | 9 | 0 |
1946```
1947
1948This worksheet can be built up in the order `A1:G1, A2:B4, E2:G4, A5:G5`:
1949
1950```js
1951/* Initial row */
1952var ws = XLSX.utils.aoa_to_sheet([ "SheetJS".split("") ]);
1953
1954/* Write data starting at A2 */
1955XLSX.utils.sheet_add_aoa(ws, [[1,2], [2,3], [3,4]], {origin: "A2"});
1956
1957/* Write data starting at E2 */
1958XLSX.utils.sheet_add_aoa(ws, [[5,6,7], [6,7,8], [7,8,9]], {origin:{r:1, c:4}});
1959
1960/* Append row */
1961XLSX.utils.sheet_add_aoa(ws, [[4,5,6,7,8,9,0]], {origin: -1});
1962```
1963
1964</details>
1965
1966### Array of Objects Input
1967
1968`XLSX.utils.json_to_sheet` takes an array of objects and returns a worksheet
1969with automatically-generated "headers" based on the keys of the objects. The
1970default column order is determined by the first appearance of the field using
1971`Object.keys`, but can be overridden using the options argument:
1972
1973| Option Name | Default | Description |
1974| :---------- | :------: | :-------------------------------------------------- |
1975|`header` | | Use specified column order (default `Object.keys`) |
1976|`dateNF` | FMT 14 | Use specified date format in string output |
1977|`cellDates` | false | Store dates as type `d` (default is `n`) |
1978|`skipHeader` | false | If true, do not include header row in output |
1979
1980<details>
1981 <summary><b>Examples</b> (click to show)</summary>
1982
1983The original sheet cannot be reproduced using plain objects since JS object keys
1984must be unique. After replacing the second `e` and `S` with `e_1` and `S_1`:
1985
1986```js
1987var ws = XLSX.utils.json_to_sheet([
1988 { S:1, h:2, e:3, e_1:4, t:5, J:6, S_1:7 },
1989 { S:2, h:3, e:4, e_1:5, t:6, J:7, S_1:8 }
1990], {header:["S","h","e","e_1","t","J","S_1"]});
1991```
1992
1993Alternatively, the header row can be skipped:
1994
1995```js
1996var ws = XLSX.utils.json_to_sheet([
1997 { A:"S", B:"h", C:"e", D:"e", E:"t", F:"J", G:"S" },
1998 { A: 1, B: 2, C: 3, D: 4, E: 5, F: 6, G: 7 },
1999 { A: 2, B: 3, C: 4, D: 5, E: 6, F: 7, G: 8 }
2000], {header:["A","B","C","D","E","F","G"], skipHeader:true});
2001```
2002
2003</details>
2004
2005`XLSX.utils.sheet_add_json` takes an array of objects and updates an existing
2006worksheet object. It follows the same process as `json_to_sheet` and accepts
2007an options argument:
2008
2009| Option Name | Default | Description |
2010| :---------- | :------: | :-------------------------------------------------- |
2011|`header` | | Use specified column order (default `Object.keys`) |
2012|`dateNF` | FMT 14 | Use specified date format in string output |
2013|`cellDates` | false | Store dates as type `d` (default is `n`) |
2014|`skipHeader` | false | If true, do not include header row in output |
2015|`origin` | | Use specified cell as starting point (see below) |
2016
2017`origin` is expected to be one of:
2018
2019| `origin` | Description |
2020| :--------------- | :-------------------------------------------------------- |
2021| (cell object) | Use specified cell (cell object) |
2022| (string) | Use specified cell (A1-style cell) |
2023| (number >= 0) | Start from the first column at specified row (0-indexed) |
2024| -1 | Append to bottom of worksheet starting on first column |
2025| (default) | Start from cell A1 |
2026
2027
2028<details>
2029 <summary><b>Examples</b> (click to show)</summary>
2030
2031Consider the worksheet:
2032
2033```
2034XXX| A | B | C | D | E | F | G |
2035---+---+---+---+---+---+---+---+
2036 1 | S | h | e | e | t | J | S |
2037 2 | 1 | 2 | | | 5 | 6 | 7 |
2038 3 | 2 | 3 | | | 6 | 7 | 8 |
2039 4 | 3 | 4 | | | 7 | 8 | 9 |
2040 5 | 4 | 5 | 6 | 7 | 8 | 9 | 0 |
2041```
2042
2043This worksheet can be built up in the order `A1:G1, A2:B4, E2:G4, A5:G5`:
2044
2045```js
2046/* Initial row */
2047var ws = XLSX.utils.json_to_sheet([
2048 { A: "S", B: "h", C: "e", D: "e", E: "t", F: "J", G: "S" }
2049], {header: ["A", "B", "C", "D", "E", "F", "G"], skipHeader: true});
2050
2051/* Write data starting at A2 */
2052XLSX.utils.sheet_add_json(ws, [
2053 { A: 1, B: 2 }, { A: 2, B: 3 }, { A: 3, B: 4 }
2054], {skipHeader: true, origin: "A2"});
2055
2056/* Write data starting at E2 */
2057XLSX.utils.sheet_add_json(ws, [
2058 { A: 5, B: 6, C: 7 }, { A: 6, B: 7, C: 8 }, { A: 7, B: 8, C: 9 }
2059], {skipHeader: true, origin: { r: 1, c: 4 }, header: [ "A", "B", "C" ]});
2060
2061/* Append row */
2062XLSX.utils.sheet_add_json(ws, [
2063 { A: 4, B: 5, C: 6, D: 7, E: 8, F: 9, G: 0 }
2064], {header: ["A", "B", "C", "D", "E", "F", "G"], skipHeader: true, origin: -1});
2065```
2066
2067</details>
2068
2069### HTML Table Input
2070
2071`XLSX.utils.table_to_sheet` takes a table DOM element and returns a worksheet
2072resembling the input table. Numbers are parsed. All other data will be stored
2073as strings.
2074
2075`XLSX.utils.table_to_book` produces a minimal workbook based on the worksheet.
2076
2077Both functions accept options arguments:
2078
2079| Option Name | Default | Description |
2080| :---------- | :------: | :-------------------------------------------------- |
2081|`raw` | | If true, every cell will hold raw strings |
2082|`dateNF` | FMT 14 | Use specified date format in string output |
2083|`cellDates` | false | Store dates as type `d` (default is `n`) |
2084|`sheetRows` | 0 | If >0, read the first `sheetRows` rows of the table |
2085|`display` | false | If true, hidden rows and cells will not be parsed |
2086
2087
2088<details>
2089 <summary><b>Examples</b> (click to show)</summary>
2090
2091To generate the example sheet, start with the HTML table:
2092
2093```html
2094<table id="sheetjs">
2095<tr><td>S</td><td>h</td><td>e</td><td>e</td><td>t</td><td>J</td><td>S</td></tr>
2096<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td></tr>
2097<tr><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td></tr>
2098</table>
2099```
2100
2101To process the table:
2102
2103```js
2104var tbl = document.getElementById('sheetjs');
2105var wb = XLSX.utils.table_to_book(tbl);
2106```
2107</details>
2108
2109Note: `XLSX.read` can handle HTML represented as strings.
2110
2111### Formulae Output
2112
2113`XLSX.utils.sheet_to_formulae` generates an array of commands that represent
2114how a person would enter data into an application. Each entry is of the form
2115`A1-cell-address=formula-or-value`. String literals are prefixed with a `'` in
2116accordance with Excel.
2117
2118<details>
2119 <summary><b>Examples</b> (click to show)</summary>
2120
2121For the example sheet:
2122
2123```js
2124> var o = XLSX.utils.sheet_to_formulae(ws);
2125> [o[0], o[5], o[10], o[15], o[20]];
2126[ 'A1=\'S', 'F1=\'J', 'D2=4', 'B3=3', 'G3=8' ]
2127```
2128</details>
2129
2130### Delimiter-Separated Output
2131
2132As an alternative to the `writeFile` CSV type, `XLSX.utils.sheet_to_csv` also
2133produces CSV output. The function takes an options argument:
2134
2135| Option Name | Default | Description |
2136| :---------- | :------: | :-------------------------------------------------- |
2137|`FS` | `","` | "Field Separator" delimiter between fields |
2138|`RS` | `"\n"` | "Record Separator" delimiter between rows |
2139|`dateNF` | FMT 14 | Use specified date format in string output |
2140|`strip` | false | Remove trailing field separators in each record ** |
2141|`blankrows` | true | Include blank lines in the CSV output |
2142|`skipHidden` | false | Skips hidden rows/columns in the CSV output |
2143
2144- `strip` will remove trailing commas from each line under default `FS/RS`
2145- `blankrows` must be set to `false` to skip blank lines.
2146
2147<details>
2148 <summary><b>Examples</b> (click to show)</summary>
2149
2150For the example sheet:
2151
2152```js
2153> console.log(XLSX.utils.sheet_to_csv(ws));
2154S,h,e,e,t,J,S
21551,2,3,4,5,6,7
21562,3,4,5,6,7,8
2157> console.log(XLSX.utils.sheet_to_csv(ws, {FS:"\t"}));
2158S h e e t J S
21591 2 3 4 5 6 7
21602 3 4 5 6 7 8
2161> console.log(XLSX.utils.sheet_to_csv(ws,{FS:":",RS:"|"}));
2162S:h:e:e:t:J:S|1:2:3:4:5:6:7|2:3:4:5:6:7:8|
2163```
2164</details>
2165
2166#### UTF-16 Unicode Text
2167
2168The `txt` output type uses the tab character as the field separator. If the
2169`codepage` library is available (included in full distribution but not core),
2170the output will be encoded in `CP1200` and the BOM will be prepended.
2171
2172`XLSX.utils.sheet_to_txt` takes the same arguments as `sheet_to_csv`.
2173
2174### HTML Output
2175
2176As an alternative to the `writeFile` HTML type, `XLSX.utils.sheet_to_html` also
2177produces HTML output. The function takes an options argument:
2178
2179| Option Name | Default | Description |
2180| :---------- | :------: | :-------------------------------------------------- |
2181|`id` | | Specify the `id` attribute for the `TABLE` element |
2182|`editable` | false | If true, set `contenteditable="true"` for every TD |
2183|`header` | | Override header (default `html body`) |
2184|`footer` | | Override footer (default `/body /html`) |
2185
2186<details>
2187 <summary><b>Examples</b> (click to show)</summary>
2188
2189For the example sheet:
2190
2191```js
2192> console.log(XLSX.utils.sheet_to_html(ws));
2193// ...
2194```
2195</details>
2196
2197### JSON
2198
2199`XLSX.utils.sheet_to_json` generates different types of JS objects. The function
2200takes an options argument:
2201
2202| Option Name | Default | Description |
2203| :---------- | :------: | :-------------------------------------------------- |
2204|`raw` | `true` | Use raw values (true) or formatted strings (false) |
2205|`range` | from WS | Override Range (see table below) |
2206|`header` | | Control output format (see table below) |
2207|`dateNF` | FMT 14 | Use specified date format in string output |
2208|`defval` | | Use specified value in place of null or undefined |
2209|`blankrows` | ** | Include blank lines in the output ** |
2210
2211- `raw` only affects cells which have a format code (`.z`) field or a formatted
2212 text (`.w`) field.
2213- If `header` is specified, the first row is considered a data row; if `header`
2214 is not specified, the first row is the header row and not considered data.
2215- When `header` is not specified, the conversion will automatically disambiguate
2216 header entries by affixing `_` and a count starting at `1`. For example, if
2217 three columns have header `foo` the output fields are `foo`, `foo_1`, `foo_2`
2218- `null` values are returned when `raw` is true but are skipped when false.
2219- If `defval` is not specified, null and undefined values are skipped normally.
2220 If specified, all null and undefined points will be filled with `defval`
2221- When `header` is `1`, the default is to generate blank rows. `blankrows` must
2222 be set to `false` to skip blank rows.
2223- When `header` is not `1`, the default is to skip blank rows. `blankrows` must
2224 be true to generate blank rows
2225
2226`range` is expected to be one of:
2227
2228| `range` | Description |
2229| :--------------- | :-------------------------------------------------------- |
2230| (number) | Use worksheet range but set starting row to the value |
2231| (string) | Use specified range (A1-style bounded range string) |
2232| (default) | Use worksheet range (`ws['!ref']`) |
2233
2234`header` is expected to be one of:
2235
2236| `header` | Description |
2237| :--------------- | :-------------------------------------------------------- |
2238| `1` | Generate an array of arrays ("2D Array") |
2239| `"A"` | Row object keys are literal column labels |
2240| array of strings | Use specified strings as keys in row objects |
2241| (default) | Read and disambiguate first row as keys |
2242
2243If header is not `1`, the row object will contain the non-enumerable property
2244`__rowNum__` that represents the row of the sheet corresponding to the entry.
2245
2246<details>
2247 <summary><b>Examples</b> (click to show)</summary>
2248
2249For the example sheet:
2250
2251```js
2252> XLSX.utils.sheet_to_json(ws);
2253[ { S: 1, h: 2, e: 3, e_1: 4, t: 5, J: 6, S_1: 7 },
2254 { S: 2, h: 3, e: 4, e_1: 5, t: 6, J: 7, S_1: 8 } ]
2255
2256> XLSX.utils.sheet_to_json(ws, {header:"A"});
2257[ { A: 'S', B: 'h', C: 'e', D: 'e', E: 't', F: 'J', G: 'S' },
2258 { A: '1', B: '2', C: '3', D: '4', E: '5', F: '6', G: '7' },
2259 { A: '2', B: '3', C: '4', D: '5', E: '6', F: '7', G: '8' } ]
2260
2261> XLSX.utils.sheet_to_json(ws, {header:["A","E","I","O","U","6","9"]});
2262[ { '6': 'J', '9': 'S', A: 'S', E: 'h', I: 'e', O: 'e', U: 't' },
2263 { '6': '6', '9': '7', A: '1', E: '2', I: '3', O: '4', U: '5' },
2264 { '6': '7', '9': '8', A: '2', E: '3', I: '4', O: '5', U: '6' } ]
2265
2266> XLSX.utils.sheet_to_json(ws, {header:1});
2267[ [ 'S', 'h', 'e', 'e', 't', 'J', 'S' ],
2268 [ '1', '2', '3', '4', '5', '6', '7' ],
2269 [ '2', '3', '4', '5', '6', '7', '8' ] ]
2270```
2271
2272Example showing the effect of `raw`:
2273
2274```js
2275> ws['A2'].w = "3"; // set A2 formatted string value
2276
2277> XLSX.utils.sheet_to_json(ws, {header:1, raw:false});
2278[ [ 'S', 'h', 'e', 'e', 't', 'J', 'S' ],
2279 [ '3', '2', '3', '4', '5', '6', '7' ], // <-- A2 uses the formatted string
2280 [ '2', '3', '4', '5', '6', '7', '8' ] ]
2281
2282> XLSX.utils.sheet_to_json(ws, {header:1});
2283[ [ 'S', 'h', 'e', 'e', 't', 'J', 'S' ],
2284 [ 1, 2, 3, 4, 5, 6, 7 ], // <-- A2 uses the raw value
2285 [ 2, 3, 4, 5, 6, 7, 8 ] ]
2286```
2287</details>
2288
2289## File Formats
2290
2291Despite the library name `xlsx`, it supports numerous spreadsheet file formats:
2292
2293| Format | Read | Write |
2294|:-------------------------------------------------------------|:-----:|:-----:|
2295| **Excel Worksheet/Workbook Formats** |:-----:|:-----:|
2296| Excel 2007+ XML Formats (XLSX/XLSM) | :o: | :o: |
2297| Excel 2007+ Binary Format (XLSB BIFF12) | :o: | :o: |
2298| Excel 2003-2004 XML Format (XML "SpreadsheetML") | :o: | :o: |
2299| Excel 97-2004 (XLS BIFF8) | :o: | :o: |
2300| Excel 5.0/95 (XLS BIFF5) | :o: | :o: |
2301| Excel 4.0 (XLS/XLW BIFF4) | :o: | |
2302| Excel 3.0 (XLS BIFF3) | :o: | |
2303| Excel 2.0/2.1 (XLS BIFF2) | :o: | :o: |
2304| **Excel Supported Text Formats** |:-----:|:-----:|
2305| Delimiter-Separated Values (CSV/TXT) | :o: | :o: |
2306| Data Interchange Format (DIF) | :o: | :o: |
2307| Symbolic Link (SYLK/SLK) | :o: | :o: |
2308| Lotus Formatted Text (PRN) | :o: | :o: |
2309| UTF-16 Unicode Text (TXT) | :o: | :o: |
2310| **Other Workbook/Worksheet Formats** |:-----:|:-----:|
2311| OpenDocument Spreadsheet (ODS) | :o: | :o: |
2312| Flat XML ODF Spreadsheet (FODS) | :o: | :o: |
2313| Uniform Office Format Spreadsheet (标文通 UOS1/UOS2) | :o: | |
2314| dBASE II/III/IV / Visual FoxPro (DBF) | :o: | :o: |
2315| Lotus 1-2-3 (WKS/WK1/WK2/WK3/WK4/123) | :o: | |
2316| Quattro Pro Spreadsheet (WQ1/WQ2/WB1/WB2/WB3/QPW) | :o: | |
2317| **Other Common Spreadsheet Output Formats** |:-----:|:-----:|
2318| HTML Tables | :o: | :o: |
2319| Rich Text Format tables (RTF) | | :o: |
2320| Ethercalc Record Format (ETH) | :o: | :o: |
2321
2322Features not supported by a given file format will not be written. Formats with
2323range limits will be silently truncated:
2324
2325| Format | Last Cell | Max Cols | Max Rows |
2326|:------------------------------------------|:-----------|---------:|---------:|
2327| Excel 2007+ XML Formats (XLSX/XLSM) | XFD1048576 | 16384 | 1048576 |
2328| Excel 2007+ Binary Format (XLSB BIFF12) | XFD1048576 | 16384 | 1048576 |
2329| Excel 97-2004 (XLS BIFF8) | IV65536 | 256 | 65536 |
2330| Excel 5.0/95 (XLS BIFF5) | IV16384 | 256 | 16384 |
2331| Excel 2.0/2.1 (XLS BIFF2) | IV16384 | 256 | 16384 |
2332
2333Excel 2003 SpreadsheetML range limits are governed by the version of Excel and
2334are not enforced by the writer.
2335
2336### Excel 2007+ XML (XLSX/XLSM)
2337
2338<details>
2339 <summary>(click to show)</summary>
2340
2341XLSX and XLSM files are ZIP containers containing a series of XML files in
2342accordance with the Open Packaging Conventions (OPC). The XLSM format, almost
2343identical to XLSX, is used for files containing macros.
2344
2345The format is standardized in ECMA-376 and later in ISO/IEC 29500. Excel does
2346not follow the specification, and there are additional documents discussing how
2347Excel deviates from the specification.
2348
2349</details>
2350
2351### Excel 2.0-95 (BIFF2/BIFF3/BIFF4/BIFF5)
2352
2353<details>
2354 <summary>(click to show)</summary>
2355
2356BIFF 2/3 XLS are single-sheet streams of binary records. Excel 4 introduced
2357the concept of a workbook (`XLW` files) but also had single-sheet `XLS` format.
2358The structure is largely similar to the Lotus 1-2-3 file formats. BIFF5/8/12
2359extended the format in various ways but largely stuck to the same record format.
2360
2361There is no official specification for any of these formats. Excel 95 can write
2362files in these formats, so record lengths and fields were determined by writing
2363in all of the supported formats and comparing files. Excel 2016 can generate
2364BIFF5 files, enabling a full suite of file tests starting from XLSX or BIFF2.
2365
2366</details>
2367
2368### Excel 97-2004 Binary (BIFF8)
2369
2370<details>
2371 <summary>(click to show)</summary>
2372
2373BIFF8 exclusively uses the Compound File Binary container format, splitting some
2374content into streams within the file. At its core, it still uses an extended
2375version of the binary record format from older versions of BIFF.
2376
2377The `MS-XLS` specification covers the basics of the file format, and other
2378specifications expand on serialization of features like properties.
2379
2380</details>
2381
2382### Excel 2003-2004 (SpreadsheetML)
2383
2384<details>
2385 <summary>(click to show)</summary>
2386
2387Predating XLSX, SpreadsheetML files are simple XML files. There is no official
2388and comprehensive specification, although MS has released documentation on the
2389format. Since Excel 2016 can generate SpreadsheetML files, mapping features is
2390pretty straightforward.
2391
2392</details>
2393
2394### Excel 2007+ Binary (XLSB, BIFF12)
2395
2396<details>
2397 <summary>(click to show)</summary>
2398
2399Introduced in parallel with XLSX, the XLSB format combines the BIFF architecture
2400with the content separation and ZIP container of XLSX. For the most part nodes
2401in an XLSX sub-file can be mapped to XLSB records in a corresponding sub-file.
2402
2403The `MS-XLSB` specification covers the basics of the file format, and other
2404specifications expand on serialization of features like properties.
2405
2406</details>
2407
2408### Delimiter-Separated Values (CSV/TXT)
2409
2410<details>
2411 <summary>(click to show)</summary>
2412
2413Excel CSV deviates from RFC4180 in a number of important ways. The generated
2414CSV files should generally work in Excel although they may not work in RFC4180
2415compatible readers. The parser should generally understand Excel CSV. The
2416writer proactively generates cells for formulae if values are unavailable.
2417
2418Excel TXT uses tab as the delimiter and code page 1200.
2419
2420Notes:
2421
2422- Like in Excel, files starting with `0x49 0x44 ("ID")` are treated as Symbolic
2423 Link files. Unlike Excel, if the file does not have a valid SYLK header, it
2424 will be proactively reinterpreted as CSV. There are some files with semicolon
2425 delimiter that align with a valid SYLK file. For the broadest compatibility,
2426 all cells with the value of `ID` are automatically wrapped in double-quotes.
2427
2428</details>
2429
2430### Other Workbook Formats
2431
2432<details>
2433 <summary>(click to show)</summary>
2434
2435Support for other formats is generally far XLS/XLSB/XLSX support, due in large
2436part to a lack of publicly available documentation. Test files were produced in
2437the respective apps and compared to their XLS exports to determine structure.
2438The main focus is data extraction.
2439
2440</details>
2441
2442#### Lotus 1-2-3 (WKS/WK1/WK2/WK3/WK4/123)
2443
2444<details>
2445 <summary>(click to show)</summary>
2446
2447The Lotus formats consist of binary records similar to the BIFF structure. Lotus
2448did release a specification decades ago covering the original WK1 format. Other
2449features were deduced by producing files and comparing to Excel support.
2450
2451</details>
2452
2453#### Quattro Pro (WQ1/WQ2/WB1/WB2/WB3/QPW)
2454
2455<details>
2456 <summary>(click to show)</summary>
2457
2458The Quattro Pro formats use binary records in the same way as BIFF and Lotus.
2459Some of the newer formats (namely WB3 and QPW) use a CFB enclosure just like
2460BIFF8 XLS.
2461
2462</details>
2463
2464#### OpenDocument Spreadsheet (ODS/FODS)
2465
2466<details>
2467 <summary>(click to show)</summary>
2468
2469ODS is an XML-in-ZIP format akin to XLSX while FODS is an XML format akin to
2470SpreadsheetML. Both are detailed in the OASIS standard, but tools like LO/OO
2471add undocumented extensions. The parsers and writers do not implement the full
2472standard, instead focusing on parts necessary to extract and store raw data.
2473
2474</details>
2475
2476#### Uniform Office Spreadsheet (UOS1/2)
2477
2478<details>
2479 <summary>(click to show)</summary>
2480
2481UOS is a very similar format, and it comes in 2 varieties corresponding to ODS
2482and FODS respectively. For the most part, the difference between the formats
2483is in the names of tags and attributes.
2484
2485</details>
2486
2487### Other Single-Worksheet Formats
2488
2489Many older formats supported only one worksheet:
2490
2491#### dBASE and Visual FoxPro (DBF)
2492
2493<details>
2494 <summary>(click to show)</summary>
2495
2496DBF is really a typed table format: each column can only hold one data type and
2497each record omits type information. The parser generates a header row and
2498inserts records starting at the second row of the worksheet. The writer makes
2499files compatible with Visual FoxPro extensions.
2500
2501Multi-file extensions like external memos and tables are currently unsupported,
2502limited by the general ability to read arbitrary files in the web browser. The
2503reader understands DBF Level 7 extensions like DATETIME.
2504
2505</details>
2506
2507#### Symbolic Link (SYLK)
2508
2509<details>
2510 <summary>(click to show)</summary>
2511
2512There is no real documentation. All knowledge was gathered by saving files in
2513various versions of Excel to deduce the meaning of fields. Notes:
2514
2515- Plain formulae are stored in the RC form.
2516- Column widths are rounded to integral characters.
2517
2518</details>
2519
2520#### Lotus Formatted Text (PRN)
2521
2522<details>
2523 <summary>(click to show)</summary>
2524
2525There is no real documentation, and in fact Excel treats PRN as an output-only
2526file format. Nevertheless we can guess the column widths and reverse-engineer
2527the original layout. Excel's 240 character width limitation is not enforced.
2528
2529</details>
2530
2531#### Data Interchange Format (DIF)
2532
2533<details>
2534 <summary>(click to show)</summary>
2535
2536There is no unified definition. Visicalc DIF differs from Lotus DIF, and both
2537differ from Excel DIF. Where ambiguous, the parser/writer follows the expected
2538behavior from Excel. In particular, Excel extends DIF in incompatible ways:
2539
2540- Since Excel automatically converts numbers-as-strings to numbers, numeric
2541 string constants are converted to formulae: `"0.3" -> "=""0.3""`
2542- DIF technically expects numeric cells to hold the raw numeric data, but Excel
2543 permits formatted numbers (including dates)
2544- DIF technically has no support for formulae, but Excel will automatically
2545 convert plain formulae. Array formulae are not preserved.
2546
2547</details>
2548
2549#### HTML
2550
2551<details>
2552 <summary>(click to show)</summary>
2553
2554Excel HTML worksheets include special metadata encoded in styles. For example,
2555`mso-number-format` is a localized string containing the number format. Despite
2556the metadata the output is valid HTML, although it does accept bare `&` symbols.
2557
2558The writer adds type metadata to the TD elements via the `t` tag. The parser
2559looks for those tags and overrides the default interpretation. For example, text
2560like `<td>12345</td>` will be parsed as numbers but `<td t="s">12345</td>` will
2561be parsed as text.
2562
2563</details>
2564
2565#### Rich Text Format (RTF)
2566
2567<details>
2568 <summary>(click to show)</summary>
2569
2570Excel RTF worksheets are stored in clipboard when copying cells or ranges from a
2571worksheet. The supported codes are a subset of the Word RTF support.
2572
2573</details>
2574
2575#### Ethercalc Record Format (ETH)
2576
2577<details>
2578 <summary>(click to show)</summary>
2579
2580[Ethercalc](https://ethercalc.net/) is an open source web spreadsheet powered by
2581a record format reminiscent of SYLK wrapped in a MIME multi-part message.
2582
2583</details>
2584
2585
2586## Testing
2587
2588### Node
2589
2590<details>
2591 <summary>(click to show)</summary>
2592
2593`make test` will run the node-based tests. By default it runs tests on files in
2594every supported format. To test a specific file type, set `FMTS` to the format
2595you want to test. Feature-specific tests are available with `make test_misc`
2596
2597```bash
2598$ make test_misc # run core tests
2599$ make test # run full tests
2600$ make test_xls # only use the XLS test files
2601$ make test_xlsx # only use the XLSX test files
2602$ make test_xlsb # only use the XLSB test files
2603$ make test_xml # only use the XML test files
2604$ make test_ods # only use the ODS test files
2605```
2606
2607To enable all errors, set the environment variable `WTF=1`:
2608
2609```bash
2610$ make test # run full tests
2611$ WTF=1 make test # enable all error messages
2612```
2613
2614`flow` and `eslint` checks are available:
2615
2616```bash
2617$ make lint # eslint checks
2618$ make flow # make lint + Flow checking
2619$ make tslint # check TS definitions
2620```
2621
2622</details>
2623
2624### Browser
2625
2626<details>
2627 <summary>(click to show)</summary>
2628
2629The core in-browser tests are available at `tests/index.html` within this repo.
2630Start a local server and navigate to that directory to run the tests.
2631`make ctestserv` will start a server on port 8000.
2632
2633`make ctest` will generate the browser fixtures. To add more files, edit the
2634`tests/fixtures.lst` file and add the paths.
2635
2636To run the full in-browser tests, clone the repo for
2637[`oss.sheetjs.com`](https://github.com/SheetJS/SheetJS.github.io) and replace
2638the `xlsx.js` file (then open a browser window and go to `stress.html`):
2639
2640```bash
2641$ cp xlsx.js ../SheetJS.github.io
2642$ cd ../SheetJS.github.io
2643$ simplehttpserver # or "python -mSimpleHTTPServer" or "serve"
2644$ open -a Chromium.app http://localhost:8000/stress.html
2645```
2646</details>
2647
2648### Tested Environments
2649
2650<details>
2651 <summary>(click to show)</summary>
2652
2653 - NodeJS `0.8`, `0.10`, `0.12`, `4.x`, `5.x`, `6.x`, `7.x`, `8.x`
2654 - IE 6/7/8/9/10/11 (IE 6-9 require shims)
2655 - Chrome 24+ (including Android 4.0+)
2656 - Safari 6+ (iOS and Desktop)
2657 - Edge 13+, FF 18+, and Opera 12+
2658
2659Tests utilize the mocha testing framework. Travis-CI and Sauce Labs links:
2660
2661 - <https://travis-ci.org/SheetJS/js-xlsx> for XLSX module in nodejs
2662 - <https://semaphoreci.com/sheetjs/js-xlsx> for XLSX module in nodejs
2663 - <https://travis-ci.org/SheetJS/SheetJS.github.io> for XLS\* modules
2664 - <https://saucelabs.com/u/sheetjs> for XLS\* modules using Sauce Labs
2665
2666The Travis-CI test suite also includes tests for various time zones. To change
2667the timezone locally, set the TZ environment variable:
2668
2669```bash
2670$ env TZ="Asia/Kolkata" WTF=1 make test_misc
2671```
2672
2673</details>
2674
2675### Test Files
2676
2677Test files are housed in [another repo](https://github.com/SheetJS/test_files).
2678
2679Running `make init` will refresh the `test_files` submodule and get the files.
2680Note that this requires `svn`, `git`, `hg` and other commands that may not be
2681available. If `make init` fails, please download the latest version of the test
2682files snapshot from [the repo](https://github.com/SheetJS/test_files/releases)
2683
2684<details>
2685 <summary><b>Latest Snapshot</b> (click to show)</summary>
2686
2687Latest test files snapshot:
2688<http://github.com/SheetJS/test_files/releases/download/20170409/test_files.zip>
2689
2690(download and unzip to the `test_files` subdirectory)
2691
2692</details>
2693
2694## Contributing
2695
2696Due to the precarious nature of the Open Specifications Promise, it is very
2697important to ensure code is cleanroom. [Contribution Notes](CONTRIBUTING.md)
2698
2699<details>
2700 <summary><b>File organization</b> (click to show)</summary>
2701
2702At a high level, the final script is a concatenation of the individual files in
2703the `bits` folder. Running `make` should reproduce the final output on all
2704platforms. The README is similarly split into bits in the `docbits` folder.
2705
2706Folders:
2707
2708| folder | contents |
2709|:-------------|:--------------------------------------------------------------|
2710| `bits` | raw source files that make up the final script |
2711| `docbits` | raw markdown files that make up `README.md` |
2712| `bin` | server-side bin scripts (`xlsx.njs`) |
2713| `dist` | dist files for web browsers and nonstandard JS environments |
2714| `demos` | demo projects for platforms like ExtendScript and Webpack |
2715| `tests` | browser tests (run `make ctest` to rebuild) |
2716| `types` | typescript definitions and tests |
2717| `misc` | miscellaneous supporting scripts |
2718| `test_files` | test files (pulled from the test files repository) |
2719
2720</details>
2721
2722After cloning the repo, running `make help` will display a list of commands.
2723
2724### OSX/Linux
2725
2726<details>
2727 <summary>(click to show)</summary>
2728
2729The `xlsx.js` file is constructed from the files in the `bits` subdirectory. The
2730build script (run `make`) will concatenate the individual bits to produce the
2731script. Before submitting a contribution, ensure that running make will produce
2732the `xlsx.js` file exactly. The simplest way to test is to add the script:
2733
2734```bash
2735$ git add xlsx.js
2736$ make clean
2737$ make
2738$ git diff xlsx.js
2739```
2740
2741To produce the dist files, run `make dist`. The dist files are updated in each
2742version release and *should not be committed between versions*.
2743</details>
2744
2745### Windows
2746
2747<details>
2748 <summary>(click to show)</summary>
2749
2750The included `make.cmd` script will build `xlsx.js` from the `bits` directory.
2751Building is as simple as:
2752
2753```cmd
2754> make
2755```
2756
2757To prepare development environment:
2758
2759```cmd
2760> make init
2761```
2762
2763The full list of commands available in Windows are displayed in `make help`:
2764
2765```
2766make init -- install deps and global modules
2767make lint -- run eslint linter
2768make test -- run mocha test suite
2769make misc -- run smaller test suite
2770make book -- rebuild README and summary
2771make help -- display this message
2772```
2773
2774As explained in [Test Files](#test-files), on Windows the release ZIP file must
2775be downloaded and extracted. If Bash on Windows is available, it is possible
2776to run the OSX/Linux workflow. The following steps prepares the environment:
2777
2778```bash
2779# Install support programs for the build and test commands
2780sudo apt-get install make git subversion mercurial
2781
2782# Install nodejs and NPM within the WSL
2783wget -qO- https://deb.nodesource.com/setup_8.x | sudo bash
2784sudo apt-get install nodejs
2785
2786# Install dev dependencies
2787sudo npm install -g mocha voc blanket xlsjs
2788```
2789
2790</details>
2791
2792### Tests
2793
2794<details>
2795 <summary>(click to show)</summary>
2796
2797The `test_misc` target (`make test_misc` on Linux/OSX / `make misc` on Windows)
2798runs the targeted feature tests. It should take 5-10 seconds to perform feature
2799tests without testing against the entire test battery. New features should be
2800accompanied with tests for the relevant file formats and features.
2801
2802For tests involving the read side, an appropriate feature test would involve
2803reading an existing file and checking the resulting workbook object. If a
2804parameter is involved, files should be read with different values to verify that
2805the feature is working as expected.
2806
2807For tests involving a new write feature which can already be parsed, appropriate
2808feature tests would involve writing a workbook with the feature and then opening
2809and verifying that the feature is preserved.
2810
2811For tests involving a new write feature without an existing read ability, please
2812add a feature test to the kitchen sink `tests/write.js`.
2813</details>
2814
2815## License
2816
2817Please consult the attached LICENSE file for details. All rights not explicitly
2818granted by the Apache 2.0 License are reserved by the Original Author.
2819
2820
2821## References
2822
2823<details>
2824 <summary><b>OSP-covered Specifications</b> (click to show)</summary>
2825
2826 - `MS-CFB`: Compound File Binary File Format
2827 - `MS-CTXLS`: Excel Custom Toolbar Binary File Format
2828 - `MS-EXSPXML3`: Excel Calculation Version 2 Web Service XML Schema
2829 - `MS-ODATA`: Open Data Protocol (OData)
2830 - `MS-ODRAW`: Office Drawing Binary File Format
2831 - `MS-ODRAWXML`: Office Drawing Extensions to Office Open XML Structure
2832 - `MS-OE376`: Office Implementation Information for ECMA-376 Standards Support
2833 - `MS-OFFCRYPTO`: Office Document Cryptography Structure
2834 - `MS-OI29500`: Office Implementation Information for ISO/IEC 29500 Standards Support
2835 - `MS-OLEDS`: Object Linking and Embedding (OLE) Data Structures
2836 - `MS-OLEPS`: Object Linking and Embedding (OLE) Property Set Data Structures
2837 - `MS-OODF3`: Office Implementation Information for ODF 1.2 Standards Support
2838 - `MS-OSHARED`: Office Common Data Types and Objects Structures
2839 - `MS-OVBA`: Office VBA File Format Structure
2840 - `MS-XLDM`: Spreadsheet Data Model File Format
2841 - `MS-XLS`: Excel Binary File Format (.xls) Structure Specification
2842 - `MS-XLSB`: Excel (.xlsb) Binary File Format
2843 - `MS-XLSX`: Excel (.xlsx) Extensions to the Office Open XML SpreadsheetML File Format
2844 - `XLS`: Microsoft Office Excel 97-2007 Binary File Format Specification
2845 - `RTF`: Rich Text Format
2846
2847</details>
2848
2849- ISO/IEC 29500:2012(E) "Information technology — Document description and processing languages — Office Open XML File Formats"
2850- Open Document Format for Office Applications Version 1.2 (29 September 2011)
2851- Worksheet File Format (From Lotus) December 1984