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