UNPKG

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