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