Skip to main content

数据导出

"导出教程" 是对数据处理和导出的简单介绍。

¥The "Export Tutorial" is a gentle introduction to data processing and export.

编写练习册

¥Writing Workbooks

API

从数据生成电子表格字节(文件)

¥Generate spreadsheet bytes (file) from data

var data = XLSX.write(workbook, opts);

write 方法尝试将工作簿中的数据打包到内存中的文件中。默认情况下,会生成 XLSX 文件,但可以使用 opts 参数的 bookType 属性进行控制。基于 type 选项,数据可以存储为 "二进制字符串"、JS 字符串、Uint8Array 或 Buffer。

¥The write method attempts to package data from the workbook into a file in memory. By default, XLSX files are generated, but that can be controlled with the bookType property of the opts argument. Based on the type option, the data can be stored as a "binary string", JS string, Uint8Array or Buffer.

第二个 opts 参数是必需的。"写作选项" 涵盖了支持的属性和行为。

¥The second opts argument is required. "Writing Options" covers the supported properties and behaviors.

生成并尝试保存文件

¥Generate and attempt to save file

XLSX.writeFile(workbook, filename, opts);

writeFile 方法打包数据并尝试保存新文件。导出文件格式由 filename 的扩展名决定(SheetJS.xlsx 信号 XLSX 导出,SheetJS.xlsb 信号 XLSB 导出等)。

¥The writeFile method packages the data and attempts to save the new file. The export file format is determined by the extension of filename (SheetJS.xlsx signals XLSX export, SheetJS.xlsb signals XLSB export, etc).

第二个 opts 参数是可选的。"写作选项" 涵盖了支持的属性和行为。

¥The second opts argument is optional. "Writing Options" covers the supported properties and behaviors.

生成并尝试保存 XLSX 文件

¥Generate and attempt to save an XLSX file

XLSX.writeFileXLSX(workbook, filename, opts);

writeFile 方法嵌入了许多不同的导出函数。这对于开发者体验来说非常有用,但不适合使用当前的开发者工具进行树摇动。当仅需要 XLSX 导出时,此方法可以避免引用其他导出函数。

¥The writeFile method embeds a number of different export functions. This is great for developer experience but not amenable to tree shaking using the current developer tools. When only XLSX exports are needed, this method avoids referencing the other export functions.

第二个 opts 参数是可选的。"写作选项" 涵盖了支持的属性和行为。

¥The second opts argument is optional. "Writing Options" covers the supported properties and behaviors.

writeFilewriteFileXLSX 方法使用特定于平台的 API 来保存文件。API 通常不提供有关文件是否已创建的反馈。

¥The writeFile and writeFileXLSX methods uses platform-specific APIs to save files. The APIs do not generally provide feedback on whether files were created.

示例

¥Examples

以下是一些常见的场景(点击每个字幕即可查看代码)。

¥Here are a few common scenarios (click on each subtitle to see the code).

demos 更详细地介绍了特殊部署。

¥The demos cover special deployments in more detail.

示例:本地文件

¥Example: Local File

XLSX.writeFile 支持在 NodeJS 等平台写入本地文件。在 React Native 等其他平台中,应该使用文件数据调用 XLSX.write

¥XLSX.writeFile supports writing local files in platforms like NodeJS. In other platforms like React Native, XLSX.write should be called with file data.

XLSX.writeFile 包含了一些触发文件保存的技术:

¥XLSX.writeFile wraps a few techniques for triggering a file save:

  • URL 浏览器 API 为文件创建一个对象 URL,库通过创建链接并强制单击来使用该对象 URL。现代浏览器支持它。

    ¥URL browser API creates an object URL for the file, which the library uses by creating a link and forcing a click. It is supported in modern browsers.

  • msSaveBlob 是用于触发文件保存的 IE10+ API。

    ¥msSaveBlob is an IE10+ API for triggering a file save.

  • IE_FileSave 使用 VBScript 和 ActiveX 在 Windows XP 和 Windows 7 的 IE6+ 中编写文件。该填充程序必须包含在包含 HTML 页面中。

    ¥IE_FileSave uses VBScript and ActiveX to write a file in IE6+ for Windows XP and Windows 7. The shim must be included in the containing HTML page.

没有标准方法来确定实际文件是否已下载。

¥There is no standard way to determine if the actual file has been downloaded.

/* output format determined by filename */
XLSX.writeFile(workbook, "out.xlsb");
/* at this point, out.xlsb will have been downloaded */
Web Worker

Web Workers 中没有一个文件写入 API 可以工作。生成文件:

¥None of the file writing APIs work from Web Workers. To generate a file:

  1. 使用 XLSX.write 和类型 array 生成 Uint8Array

    ¥use XLSX.write with type array to generate a Uint8Array:

// in the web worker, generate the XLSX file as a Uint8Array
const u8 = XLSX.write(workbook, { type: "array", bookType: "xlsx" });
  1. 将数据发送回主线程:

    ¥send the data back to the main thread:

// in the web worker, send the generated data back to the main thread
postMessage({t: "export", v: u8 });
  1. 从主线程添加一个事件监听器以写入文件:

    ¥from the main thread, add an event listener to write to file:

// in the main page
worker.addEventListener('message', function(e) {
if(e && e.data && e.data.t == "export") {
e.stopPropagation();
e.preventDefault();
// data will be the Uint8Array from the worker
const data = e.data.v;

var blob = new Blob([data], {type:"application/octet-stream"});
var url = URL.createObjectURL(blob);
var a = document.createElement("a");
a.download = "SheetJSXPort.xlsx";
a.href = url;
document.body.appendChild(a);
a.click();
}
});
SWF workaround for Windows 95+ (click to show)

Each moving part in this solution has been deprecated years ago:

  • Adobe stopped supporting Flash Player at the end of 2020
  • Microsoft stopped supporting IE8 in 2019 and stopped supporting IE9 in 2020
  • Downloadify support ended in 2010 and SWFObject support ended in 2016

New projects should strongly consider requiring modern browsers. This info is provided on an "as is" basis and there is no realistic way to provide support given that every related vendor stopped providing support for their software.

XLSX.writeFile techniques work for most modern browsers as well as older IE. For much older browsers, there are workarounds implemented by wrapper libraries.

Downloadify uses a Flash SWF button to generate local files, suitable for environments where ActiveX is unavailable:

Downloadify.create(id,{
/* other options are required! read the downloadify docs for more info */
filename: "test.xlsx",
data: function() { return XLSX.write(wb, {bookType:"xlsx", type:"base64"}); },
append: false,
dataType: "base64"
});

The oldie demo shows an IE-compatible fallback scenario.

示例:服务器响应

¥Example: Server Responses

此示例重点关注 NodeJS 等服务器端平台中对网络请求的响应。虽然可以在网络浏览器中生成文件,但服务器端文件生成可以实现精确的审计跟踪,并具有更好的移动用户支持。

¥This example focuses on responses to network requests in a server-side platform like NodeJS. While files can be generated in the web browser, server-side file generation allows for exact audit trails and has better mobile user support.

生产部署应该使用像 ExpressJS 这样的服务器框架。这些代码片段使用底层 API 来进行说明。

¥Production deployments should use a server framework like ExpressJS. These snippets use low-level APIs for illustration purposes.

对于 Excel 导出(包括 XLSX),Content-Type 标头应设置为 application/vnd.ms-excel。可以使用默认的 application/octet-stream,但 iOS 不会自动建议在 Numbers 或 Excel for iOS 中打开文件

¥The Content-Type header should be set to application/vnd.ms-excel for Excel exports including XLSX. The default application/octet-stream can be used, but iOS will not automatically suggest to open files in Numbers or Excel for iOS

Content-Disposition 标头指示浏览器将响应下载到文件中。标头还可以包含所需的文件名。

¥The Content-Disposition header instructs browsers to download the response into a file. The header can also include the desired file name.

NodeJS http.ServerResponse#end 可以接受 Buffer 对象。具有 buffer 类型的 XLSX.write 返回 Buffer 对象。

¥NodeJS http.ServerResponse#end can accept Buffer objects. XLSX.write with buffer type returns Buffer objects.

/* generate Buffer */
const buf = XLSX.write(wb, { type:"buffer", bookType:"xlsx" });

/* prepare response headers */
res.statusCode = 200;
res.setHeader('Content-Disposition', 'attachment; filename="SheetJSNode.xlsx"');
res.setHeader('Content-Type', 'application/vnd.ms-excel');
res.end(buf);
Complete Example (click to show)

Install the library with

npm i --save https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz

Save the following script to node.js and run with node node.js:

node.js
const http = require('http');
const XLSX = require('xlsx');

const hostname = '127.0.0.1';
const port = 7262;

/* fixed sample worksheet */
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet([
["a","b","c"], [1,2,3]
]), "Sheet1");

const server = http.createServer((req, res) => {
const buf = XLSX.write(wb, { type:"buffer", bookType:"xlsx" });
res.statusCode = 200;
res.setHeader('Content-Disposition', 'attachment; filename="SheetJSNode.xlsx"');
res.setHeader('Content-Type', 'application/vnd.ms-excel');
res.end(buf);
});

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

示例:远程文件

¥Example: Remote File

此示例重点介绍使用 XMLHttpRequestfetch 等 API 以及第三方库上传文件(浏览器用语中的 "Ajax")。

¥This example focuses on uploading files ("Ajax" in browser parlance) using APIs like XMLHttpRequest and fetch as well as third-party libraries.

Azure 和 AWS 等某些平台会尝试将 POST 请求正文解析为 UTF-8 字符串,然后用户代码才能看到数据。这将导致服务器解析的数据损坏。有一些解决方法,但最安全的方法是调整服务器进程或 Lambda 函数以接受 Base64 字符串。

¥Some platforms like Azure and AWS will attempt to parse POST request bodies as UTF-8 strings before user code can see the data. This will result in corrupt data parsed by the server. There are some workarounds, but the safest approach is to adjust the server process or Lambda function to accept Base64 strings.

HTTP 上传演示 包括使用浏览器 API 和封装器库的示例。

¥The HTTP Uploads demo includes examples using browser APIs and wrapper libraries.

正常情况下,可以从 array 输出生成一个 Blob

¥Under normal circumstances, a Blob can be generated from the array output:

/* in this example, send a Blob to the server */
var wbout = XLSX.write(workbook, { bookType: "xlsx", type: "array" });

/* prepare data for POST */
var blob = new Blob([new Uint8Array(wbout)], {type:"application/octet-stream"});
var formdata = new FormData();
formdata.append("file", blob, "test.xlsx");

/* perform POST request */
fetch("/upload", { method: 'POST', body: formdata });

当不支持二进制数据时,应传递 Base64 字符串。这将要求服务器预期并解码数据:

¥When binary data is not supported, Base64 strings should be passed along. This will require the server to expect and decode the data:

/* in this example, send a Base64 string to the server */
var wbout = XLSX.write(workbook, { bookType: "xlsx", type: "base64" });

/* prepare data for POST */
var formdata = new FormData();
formdata.append("file", "test.xlsx"); // <-- server expects `file` to hold name
formdata.append("data", wbout); // <-- `data` holds the data encoded in Base64

/* perform POST request */
var req = new XMLHttpRequest();
req.open("POST", "/upload", true);
req.send(formdata);

生成 JSON 和 JS 数据

¥Generating JSON and JS Data

JSON 和 JS 数据往往代表单个工作表。本节中的实用函数适用于单个工作表。

¥JSON and JS data tend to represent single worksheets. The utility functions in this section work with single worksheets.

"通用电子表格格式" 部分更详细地描述了对象结构。workbook.SheetNames 是工作表名称的有序列表。workbook.Sheets 是一个对象,其键是工作表名称,其值是工作表对象。

¥The "Common Spreadsheet Format" section describes the object structure in more detail. workbook.SheetNames is an ordered list of the worksheet names. workbook.Sheets is an object whose keys are sheet names and whose values are worksheet objects.

"第一个工作表" 存储在 workbook.Sheets[workbook.SheetNames[0]] 中。

¥The "first worksheet" is stored at workbook.Sheets[workbook.SheetNames[0]].

API

从工作表创建 JS 对象数组

¥Create an array of JS objects from a worksheet

var jsa = XLSX.utils.sheet_to_json(worksheet, opts);

从工作表创建 JS 值数组的数组

¥Create an array of arrays of JS values from a worksheet

var aoa = XLSX.utils.sheet_to_json(worksheet, {...opts, header: 1});

sheet_to_json 实用程序函数按行优先顺序遍历工作簿,生成对象数组。第二个 opts 参数控制许多导出决策,包括值的类型(JS 值或格式化文本)。"数组输出" 部分描述了支持的选项。

¥The sheet_to_json utility function walks a workbook in row-major order, generating an array of objects. The second opts argument controls a number of export decisions including the type of values (JS values or formatted text). The "Array Output" section describes supported options.

默认情况下,sheet_to_json 扫描第一行并使用这些值作为标题。使用 header: 1 选项,该函数导出值数组的数组。

¥By default, sheet_to_json scans the first row and uses the values as headers. With the header: 1 option, the function exports an array of arrays of values.

示例

¥Examples

示例:数据网格

¥Example: Data Grids

x-spreadsheet 是一个交互式数据网格,用于在网络浏览器中预览和修改结构化数据。

¥x-spreadsheet is an interactive data grid for previewing and modifying structured data in the web browser.

示例:数据加载

¥Example: Data Loading

"TensorFlow.js" 涵盖了从工作表数据生成类型化数组和张量的策略。

¥"TensorFlow.js" covers strategies for generating typed arrays and tensors from worksheet data.

Populating a database (SQL or no-SQL) (click to show)

The data demo includes examples of working with databases and query results.

生成 HTML 表格

¥Generating HTML Tables

API

从工作表生成 HTML 表格

¥Generate HTML Table from Worksheet

var html = XLSX.utils.sheet_to_html(worksheet);

sheet_to_html 实用程序函数根据工作表数据生成 HTML 代码。工作表中的每个单元格都映射到 <TD> 元素。合并单元格 使用 TR 和 TH colspanrowspan 属性进行序列化。

¥The sheet_to_html utility function generates HTML code based on the worksheet data. Each cell in the worksheet is mapped to a <TD> element. Merged cells are serialized using the TR and TH colspan and rowspan attributes.

示例

¥Examples

sheet_to_html 实用程序函数生成 HTML 代码,可以通过设置 innerHTML 将其添加到任何 DOM 元素:

¥The sheet_to_html utility function generates HTML code that can be added to any DOM element by setting the innerHTML:

var container = document.getElementById("tavolo");
container.innerHTML = XLSX.utils.sheet_to_html(worksheet);

fetch 结合,从工作簿构建站点非常简单:

¥Combining with fetch, constructing a site from a workbook is straightforward:

此示例分配 DIV 元素的 innerHTML

¥This example assigns the innerHTML of a DIV element:

<body>
<style>TABLE { border-collapse: collapse; } TD { border: 1px solid; }</style>
<div id="tavolo"></div>
<script src="https://cdn.sheetjs.com/xlsx-0.20.3/package/dist/xlsx.full.min.js"></script>
<script type="text/javascript">
(async() => {
/* fetch and parse workbook -- see the fetch example for details */
const workbook = XLSX.read(await (await fetch("sheetjs.xlsx")).arrayBuffer());

let output = [];
/* loop through the worksheet names in order */
workbook.SheetNames.forEach(name => {

/* generate HTML from the corresponding worksheets */
const worksheet = workbook.Sheets[name];
const html = XLSX.utils.sheet_to_html(worksheet);

/* add a header with the title name followed by the table */
output.push(`<H3>${name}</H3>${html}`);
});
/* write to the DOM at the end */
tavolo.innerHTML = output.join("\n");
})();
</script>
</body>

生成单个工作表快照

¥Generating Single-Worksheet Snapshots

sheet_to_* 函数接受工作表对象。

¥The sheet_to_* functions accept a worksheet object.

API

从单个工作表生成 CSV

¥Generate a CSV from a single worksheet

var csv = XLSX.utils.sheet_to_csv(worksheet, opts);

此快照旨在复制“CSV UTF-8 (.csv)”输出类型。"CSV 和文本" 更详细地描述了该函数和可选的 opts 参数。

¥This snapshot is designed to replicate the "CSV UTF-8 (.csv)" output type. "CSV and Text" describes the function and the optional opts argument in more detail.

从单个工作表生成 "文本"

¥Generate "Text" from a single worksheet

var txt = XLSX.utils.sheet_to_txt(worksheet, opts);

此快照旨在复制“UTF-16 Text (.txt)”输出类型。"CSV 和文本" 更详细地描述了该函数和可选的 opts 参数。

¥This snapshot is designed to replicate the "UTF-16 Text (.txt)" output type. "CSV and Text" describes the function and the optional opts argument in more detail.

从单个工作表生成公式列表

¥Generate a list of formulae from a single worksheet

var fmla = XLSX.utils.sheet_to_formulae(worksheet);

该快照生成表示嵌入公式的条目数组。数组公式以 range=formula 形式渲染,而普通单元格以 cell=formula or value 形式渲染。字符串字面量以撇号 ' 为前缀,与 Excel 的编辑栏显示一致。

¥This snapshot generates an array of entries representing the embedded formulae. Array formulae are rendered in the form range=formula while plain cells are rendered in the form cell=formula or value. String literals are prefixed with an apostrophe ', consistent with Excel's formula bar display.

"公式输出" 更详细地描述了该功能。

¥"Formulae Output" describes the function in more detail.

流式写入

¥Streaming Write

XLSX.stream 对象中提供了流式写入功能。它们采用与普通写入函数相同的参数,但返回 NodeJS 可读流。

¥The streaming write functions are available in the XLSX.stream object. They take the same arguments as the normal write functions but return a NodeJS Readable Stream.

  • XLSX.stream.to_csvXLSX.utils.sheet_to_csv 的流式版本。

    ¥XLSX.stream.to_csv is the streaming version of XLSX.utils.sheet_to_csv.

  • XLSX.stream.to_htmlXLSX.utils.sheet_to_html 的流式版本。

    ¥XLSX.stream.to_html is the streaming version of XLSX.utils.sheet_to_html.

  • XLSX.stream.to_jsonXLSX.utils.sheet_to_json 的流式版本。

    ¥XLSX.stream.to_json is the streaming version of XLSX.utils.sheet_to_json.

  • XLSX.stream.to_xlml 是流式 SpreadsheetML2003 工作簿编写器。

    ¥XLSX.stream.to_xlml is the streaming SpreadsheetML2003 workbook writer.

"流导出" 更详细地描述了该功能。

¥"Stream Export" describes the function in more detail.