docs.sheetjs.com/docz/docs/08-api/05-write-options.md

19 KiB

sidebar_position hide_table_of_contents title
5 true Writing Files

import current from '/version.js'; import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import CodeBlock from '@theme/CodeBlock';

The main SheetJS method for writing workbooks is write. It accepts a SheetJS workbook object and returns the file data stored in common JavaScript data representations. Scripts calling write are expected to write or share files using platform-specific APIs.

The writeFile helper method accepts a filename and tries to write to a local file using standard local file APIs.

Export a SheetJS workbook object in a specified file format

var file_data = XLSX.write(wb, opts);

write attempts to write the workbook wb and return the file.

The options argument is required. It must specify

  • bookType: file format of the exported file
  • type: return value type

Export a SheetJS workbook object and attempt to write a local file

XLSX.writeFile(wb, filename, options);

writeFile attempts to write wb to a local file with specified filename.

In browser-based environments, it will attempt to force a client-side download. It also supports NodeJS, ExtendScript applications, and Chromium extensions.

The options argument is optional.

If options is omitted or if bookType is missing from the options object, the output file format will be inferred from the filename.

Special functions for exporting data in the XLSX format

/* `write` (XLSX only) */
var file_data = XLSX.writeXLSX(wb, options);

/* `writeFile` (XLSX only) */
XLSX.writeFileXLSX(wb, filename, options);

writeXLSX and writeFileXLSX are limited versions of write and writeFile. They support writing to the XLSX file format.

For websites that exclusively export to XLSX, these functions can reduce the size of the production site. The general write and writeFile functions are more appropriate when exporting to XLS or XLSB or other formats.

NodeJS-specific methods (click to show)

Export a workbook and attempt to write a local file using fs.writeFile

/* callback equivalent of `XLSX.writeFile(wb, filename)` */
XLSX.writeFileAsync(filename, wb, cb);

/* callback equivalent of `XLSX.writeFile(wb, filename, options)` */
XLSX.writeFileAsync(filename, wb, options, cb);

writeFileAsync attempts to write wb to filename and invoke the callback cb on completion.

When an options object is specified, it is expected to be the third argument.

This method only works in NodeJS. It uses fs.writeFile under the hood.

:::note Recommendation

writeFile wraps a number of export techniques, making it suitable for web browsers, Photoshop and InDesign, and server-side platforms including NodeJS. It does not work in other environments with more advanced export methods.

write returns raw bytes or strings that can be exported with platform-specific APIs in Desktop apps, Mobile apps, Servers, and extensions.

The demos preferentially use writeFile. When writeFile is not supported, the demos show file creation using write and platform APIs.

:::

:::tip pass

The SheetJS file format export codecs focus on raw data. Not all codecs support all features. Features not described in the documentation may not be serialized.

SheetJS Pro offers support for additional features, including styling, images, graphs, and PivotTables.

:::

Writing Options

The write functions accept an options argument:

Option Name Default Description
type Output data encoding
cellDates false Convert numeric date codes to strings
cellStyles false Export style/theme info
codepage Use specified code page encoding
bookSST false Generate Shared String Table
bookType "xlsx" Type of Workbook
bookVBA Add VBA blob from workbook object
WTF false Do not suppress warnings and errors
sheet "" Export the named sheet
compression false Try to reduce file size
Props Override workbook properties
themeXLSX Override theme XML for XLSX/XLSB/XLSM
ignoreEC true Suppress "number as text" errors
numbers Payload for NUMBERS export
FS "," Field Separator for CSV and Text exports
RS "\n" Record Separator for CSV and Text exports

Supported Output Formats

For broad compatibility with third-party tools, SheetJS CE supports many output formats. The writer will select the file type based on the bookType option:

bookType extension sheets Description
xlsx .xlsx multi Excel 2007+ XML Format
xlsm .xlsm multi Excel 2007+ Macro XML Format
xlsb .xlsb multi Excel 2007+ Binary Format
biff8 .xls multi Excel 97-2004 Workbook Format
biff5 .xls multi Excel 5.0/95 Workbook Format
biff4 .xls single Excel 4.0 Worksheet Format
biff3 .xls single Excel 3.0 Worksheet Format
biff2 .xls single Excel 2.0 Worksheet Format
xlml .xls multi Excel 2003-2004 (SpreadsheetML)
numbers .numbers multi Numbers 3.0+ Spreadsheet
ods .ods multi OpenDocument Spreadsheet
fods .fods multi Flat OpenDocument Spreadsheet
wk3 .wk3 multi Lotus Workbook (WK3)
csv .csv single Comma Separated Values
txt .txt single UTF-16 Unicode Text (TXT)
sylk .sylk single Symbolic Link (SYLK)
html .html single HTML Document
dif .dif single Data Interchange Format (DIF)
dbf .dbf single dBASE II + VFP Extensions (DBF)
wk1 .wk1 single Lotus Worksheet (WK1)
rtf .rtf single Rich Text Format (RTF)
prn .prn single Lotus Formatted Text
eth .eth single Ethercalc Record Format (ETH)

If the output format supports multiple worksheets, the workbook writer will try to export each worksheet. If the format only supports one worksheet, the writer will export the first worksheet. If the sheet option is a string, the writer will use the named sheet.

Output Format inference from File Extension

writeFile will automatically guess the output file format based on the file extension if bookType is not specified.

extension Description
.csv Comma Separated Values
.dbf dBASE II + VFP Extensions (DBF)
.dif Data Interchange Format (DIF)
.eth Ethercalc Record Format (ETH)
.fods Flat OpenDocument Spreadsheet
.html HTML Document
.numbers Numbers 3.0+ Spreadsheet
.ods OpenDocument Spreadsheet
.prn Lotus Formatted Text
.rtf Rich Text Format (RTF)
.sylk Symbolic Link (SYLK)
.txt UTF-16 Unicode Text (TXT)
.wk1 Lotus Worksheet (WK1)
.wk3 Lotus Workbook (WK3)
.xls Excel 97-2004 Workbook Format
.xlsb Excel 2007+ Binary Format
.xlsm Excel 2007+ Macro XML Format
.xlsx Excel 2007+ XML Format

Output Type

The type option specifies the JS form of the output:

type output
base64 string: Base64 encoding of the file
binary string: binary string (byte n is data.charCodeAt(n))
string string: JS string (not compatible with binary formats)
buffer NodeJS Buffer or Uint8Array
array ArrayBuffer or array of 8-bit unsigned int
file (attempt to download a file)

:::note pass

For compatibility with Excel, csv output will always include the UTF-8 byte order mark ("BOM").

The raw sheet_to_csv method will return JavaScript strings without the UTF-8 BOM.

:::

Other Options

Cell-Level Options

Dates

Plaintext files store dates using formatted strings. XLS and most Excel file formats store dates using numeric date codes.

XLSX and ODS/FODS support both numeric date codes and ISO 8601 date strings.

By default, when both numeric date codes and date strings are supported, the writers will export date codes. Date cells (type d) will be converted to numeric cells.

If the cellDates option is set, writers will export date strings. If number formats include date tokens, numeric cells (type n) will be converted to date cells.

:::caution pass

Generated files are not guaranteed to work with third-party spreadsheet readers! Third-party tools may ignore cells or reject files that use proper date cells.

:::

"Dates and Times" covers features in more detail.

Text and Cell Styling

By default, SheetJS CE writers focus on data preservation.

If the cellStyles option is true, other styling metadata including row and column will be exported.

:::tip pass

SheetJS Pro offers cell / text styling, conditional formatting and additional styling options.

:::

Sheet-Level Options

Error Checking

By default, Excel warns users when creating text cells when the text could be parsed as a number. People and software systems commonly use text to store US ZIP Codes, as many ZIP Codes in New Jersey start with "0".

By default, SheetJS writers add special marks to instruct Excel not to elicit warnings on cells containing text that look like numbers.

Due to a bug in Excel, "Text to Columns" and other features may lead to crashes in files where error conditions are ignored. If the ignoreEC option is explicitly set to false, SheetJS writers will not add the offending marks.

Book-Level Options

VBA

When exporting to file formats that support VBA (XLSX, XLSB, XLS), macros are not guaranteed to be exported by default. The bookVBA option should be set to a truthy value (true or 1).

The "VBA" section explains the feature in more detail.

Workbook Properties

When exporting to a file format that supports workbook properties, the SheetJS export codecs will look in the workbook object for file properties.

If the Props option is specified, the export codecs will ignore properties from the workbook object.

The "File Properties" section lists the supported file properties.

File-Level Options

Compression

XLSX, XLSB, NUMBERS, and ODS files use ZIP containers. The ZIP container format supports different levels of compression. Spreadsheet software typically use compression when exporting files.

By default, SheetJS writers optimize for speed. Exports are faster but the generated files are larger.

If the compression option is set, writers will optimize for file size. Exports are smaller but will take more time.

Target Sheet

Some output formats support multiple worksheets. By default, the SheetJS export codecs will export all worksheets.

Other output formats, including CSV and legacy Excel and Lotus worksheet files, only support one worksheet. By default, the SheetJS export codecs will use the first worksheet from the workbook.

If the sheet option is set to the name of a valid worksheet in the workbook, the SheetJS writers will use the named sheet even if it is not the first sheet.

Shared String Table (SST)

XLSX, XLS, and XLSB can store text cells in two ways.

By default, the writers use "inline" strings. The content of each text cell is stored in the cell representation. This approach is conceptually simple, but it uses features that may not be supported in iOS Numbers and other apps.

If the bookSST option is set, writers use the "shared string table" (SST) feature. A separate lookup table houses each text string and cells store indices into the SST. Multiple cells can point to the same SST entry.

Exporting with SST is typically slower and more memory intensive, but the files may be smaller and have better compatibility with third-party software.

Delimiter-Separated Values

The SheetJS CSV writer uses commas to separate fields within a row and adds line separators between rows.

The characters used to separate fields and rows can be controlled through the FS ("field separator") and RS ("row separator") options.

"CSV and Text" discusses the options in more detail.

Code Page Encoding

Spreadsheet applications support a number of legacy encodings. Plaintext files will appear different when opened in different computers in different regions.

By default, the writers use the most common "English (United States)" encodings. The codepage option controls the encoding in BIFF2 - BIFF5 XLS files without CodePage records, some legacy formats including DBF, and in CSV files without BOM in type: "binary".

Characters missing from the specified encoding will be replaced with underscore characters (_).

The codepage support library is not guaranteed to be loaded by default. The "Installation" section describes how to install and load the support library.

See "Legacy Codepages" for more details.

XLSX and XLSB Theme

By default, the SheetJS XLSX and XLSB output codecs use a predetermined theme. This simplifies column widths and other features that depend on font metrics.

If the themeXLSX option is a string, the XLSB and XLSX codecs will suppress the default theme. The default theme xl/theme/theme1.xml will be overridden.

Writing Errors

If the WTF option is enabled, workbook writers will show warnings and errors when workbooks use features that may be considered unsafe. For example, some file features are only supported in specific versions of Excel.

NUMBERS Exports

Rationale (click to hide)

Apple Numbers has broken backwards compatibility many times over the years. Files generated by older versions of Numbers are not guaranteed to work with newer versions of Numbers or third-party tools.

The NUMBERS exporter starts from a working file and rewrites the data blocks. This ensures exports still work

The current design allows for updating the base file without disrupting the rest of the library.

The numbers option is required for exporting NUMBERS files. It is expected to be a Base64 string that encodes a valid Numbers file. The supplementary xlsx.zahl scripts include the required string.

{"https://cdn.sheetjs.com/xlsx-" + current + "/package/dist/xlsx.zahl.js"} is the URL for {current}

{`\

<html><head></head>\n\ \n\ \n\ \n\ </html>`}

After installing the package:

{\ npm i --save https://cdn.sheetjs.com/xlsx-${current}/xlsx-${current}.tgz}

The scripts will be available at xlsx/dist/xlsx.zahl (CommonJS) and xlsx/dist/xlsx.zahl.mjs (ESM).

var XLSX = require("xlsx");
var XLSX_ZAHL_PAYLOAD = require("xlsx/dist/xlsx.zahl");
var wb = XLSX.utils.book_new(); var ws = XLSX.utils.aoa_to_sheet([
  ["SheetJS", "<3","விரிதாள்"],
  [72,,"Arbeitsblätter"],
  [,62,"数据"],
  [true,false,],
]); XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
XLSX.writeFile(wb, "textport.numbers", {numbers: XLSX_ZAHL_PAYLOAD, compression: true});

After installing the package:

{\ bun i https://cdn.sheetjs.com/xlsx-${current}/xlsx-${current}.tgz}

The scripts will be available at xlsx/dist/xlsx.zahl (CommonJS) and xlsx/dist/xlsx.zahl.mjs (ESM).

import * as XLSX from "xlsx";
import XLSX_ZAHL_PAYLOAD from "xlsx/dist/xlsx.zahl";
import * as fs from "fs";
XLSX.set_fs(fs);
var wb = XLSX.utils.book_new(); var ws = XLSX.utils.aoa_to_sheet([
  ["SheetJS", "<3","விரிதாள்"],
  [72,,"Arbeitsblätter"],
  [,62,"数据"],
  [true,false,],
]); XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
XLSX.writeFile(wb, "textport.numbers", {numbers: XLSX_ZAHL_PAYLOAD, compression: true});

{"https://cdn.sheetjs.com/xlsx-" + current + "/package/dist/xlsx.zahl.mjs"} is the URL for {current}

{\ import * as XLSX from 'https://cdn.sheetjs.com/xlsx-${current}/package/xlsx.mjs';\n\ import XLSX_ZAHL_PAYLOAD from 'https://cdn.sheetjs.com/xlsx-${current}/package/dist/xlsx.zahl.mjs';\n\ \n\ var wb = XLSX.utils.book_new(); var ws = XLSX.utils.aoa_to_sheet([\n\ ["SheetJS", "<3","விரிதாள்"],\n\ [72,,"Arbeitsblätter"],\n\ [,62,"数据"],\n\ [true,false,],\n\ ]); XLSX.utils.book_append_sheet(wb, ws, "Sheet1");\n\ XLSX.writeFile(wb, "textport.numbers", {numbers: XLSX_ZAHL_PAYLOAD, compression: true});\n\ }