UNPKG

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