数据导出
"导出教程" 是对数据处理和导出的简单介绍。
¥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.
writeFile 和 writeFileXLSX 方法使用特定于平台的 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.
- Browser
- NodeJS
- Bun
- Deno
- Electron
- React Native
- Photoshop
- Headless
XLSX.writeFile 包含了一些触发文件保存的技术:
¥XLSX.writeFile wraps a few techniques for triggering a file save:
-
URL浏览器 API 为文件创建一个对象 URL,库通过创建链接并强制单击来使用该对象 URL。现代浏览器支持它。¥
URLbrowser 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。¥
msSaveBlobis an IE10+ API for triggering a file save. -
IE_FileSave使用 VBScript 和 ActiveX 在 Windows XP 和 Windows 7 的 IE6+ 中编写文件。该填充程序必须包含在包含 HTML 页面中。¥
IE_FileSaveuses 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 Workers 中没有一个文件写入 API 可以工作。生成文件:
¥None of the file writing APIs work from Web Workers. To generate a file:
-
使用
XLSX.write和类型array生成Uint8Array:¥use
XLSX.writewith typearrayto generate aUint8Array:
// in the web worker, generate the XLSX file as a Uint8Array
const u8 = XLSX.write(workbook, { type: "array", bookType: "xlsx" });
-
将数据发送回主线程:
¥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 });
-
从主线程添加一个事件监听器以写入文件:
¥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 many years ago:
- Adobe discontinued Flash Player
- Microsoft discontinued Internet Explorer
DownloadifyandSWFObjectare no longer supported
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.
writeFile 在底层使用 fs.writeFileSync:
¥writeFile uses fs.writeFileSync under the hood:
var XLSX = require("xlsx");
/* output format determined by filename */
XLSX.writeFile(workbook, "out.xlsb");
对于 Node ESM,必须手动加载 fs:
¥For Node ESM, fs must be loaded manually:
import * as fs from "fs";
import { writeFile, set_fs } from "xlsx";
set_fs(fs);
/* output format determined by filename */
writeFile(workbook, "out.xlsb");
与 Node ESM 一样,必须手动加载 fs:
¥As with Node ESM, fs must be loaded manually:
import * as fs from "fs";
import { writeFile, set_fs } from "xlsx";
set_fs(fs);
/* output format determined by filename */
writeFile(workbook, "out.xlsb");
writeFile 在底层使用 Deno.writeFileSync:
¥writeFile uses Deno.writeFileSync under the hood:
// @deno-types="https://cdn.sheetjs.com/xlsx-0.20.3/package/types/index.d.ts"
import * as XLSX from 'https://cdn.sheetjs.com/xlsx-0.20.3/package/xlsx.mjs';
XLSX.writeFile(workbook, "test.xlsx");
写入文件的应用必须使用 --allow-write 标志来调用。
¥Applications writing files must be invoked with the --allow-write flag.
writeFile 可以在渲染器进程中使用:
¥writeFile can be used in the renderer process:
/* From the renderer process */
var XLSX = require("xlsx");
XLSX.writeFile(workbook, "out.xlsb");
Electron API 随着时间的推移而发生变化。electron 演示 显示了完整的示例并详细说明了所需的特定于版本的设置。
¥Electron APIs have changed over time. The electron demo
shows a complete example and details the required version-specific settings.
React Native 演示 涵盖经过测试的插件。
¥The React Native Demo covers tested plugins.
writeFile 在 Photoshop 和其他 ExtendScript 目标中封装了 File 逻辑。指定的路径应该是绝对路径:
¥writeFile wraps the File logic in Photoshop and other ExtendScript targets.
The specified path should be an absolute path:
#include "xlsx.extendscript.js"
/* Ask user to select path */
var thisFile = File.saveDialog("Select an output file", "*.xlsx;*.xls");
/* output format determined by filename */
XLSX.writeFile(workbook, thisFile.absoluteURI);
"ExtendScript" 演示 包括 Photoshop 和 InDesign 的完整示例。
¥The "ExtendScript" demo includes complete examples for Photoshop and InDesign.
headless 演示 包含使用 Puppeteer 和其他无头自动化工具将 HTML TABLE 元素转换为 XLSB 工作簿的完整示例。
¥The headless demo includes complete
examples of converting HTML TABLE elements to XLSB workbooks using Puppeteer
and other headless automation tools.
无头浏览器可能无法访问文件系统,因此 XLSX.writeFile 可能会失败。强烈建议在浏览器上下文中生成文件字节,将字节发送到自动化上下文,然后从自动化写入。
¥Headless browsers may not have access to the filesystem, so XLSX.writeFile
may fail. It is strongly recommended to generate the file bytes in the browser
context, send the bytes to the automation context, and write from automation.
Puppeteer 和 Playwright 是支持二进制字符串的 NodeJS 模块:
¥Puppeteer and Playwright are NodeJS modules that support binary strings:
/* from the browser context */
var bin = XLSX.write(workbook, { type:"binary", bookType: "xlsb" });
/* from the automation context */
fs.writeFileSync("SheetJSansHead.xlsb", bin, { encoding: "binary" });
PhantomJS fs.write 支持从主进程写入文件。模式 wb 支持二进制字符串:
¥PhantomJS fs.write supports writing files from the main process. The mode
wb supports binary strings:
/* from the browser context */
var bin = XLSX.write(workbook, { type:"binary", bookType: "xlsb" });
/* from the automation context */
fs.write("SheetJSansHead.xlsb", bin, "wb");
示例:服务器响应
¥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
- Deno
- Bun
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:
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}/`);
});
Deno 响应预计为 Response 对象。XLSX.write 和 buffer 类型返回可以在 Response 中使用的 Uint8Array 对象。
¥Deno responses are expected to be Response objects. XLSX.write with buffer
type returns Uint8Array objects that can be used in the Response.
/* generate Buffer */
const buf = XLSX.write(wb, { type:"buffer", bookType:"xlsx" });
/* return Response */
evt.respondWith(new Response(buf, {
status: 200,
headers: {
"Content-Type": "application/vnd.ms-excel",
"Content-Disposition": 'attachment; filename="SheetJSDeno.xlsx"'
}
}));
Complete Example (click to show)
Save the following script to deno.ts and run with deno run -A deno.ts. Open
a web browser and access http://localhost:7262/ to download the workbook.
// @deno-types="https://cdn.sheetjs.com/xlsx-0.20.3/package/types/index.d.ts"
import * as XLSX from 'https://cdn.sheetjs.com/xlsx-0.20.3/package/xlsx.mjs';
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet([
["a","b","c"], [1,2,3]
]), "Sheet1");
async function doNotAwaitThis(conn: Deno.Conn) {
for await (const e of Deno.serveHttp(conn)) e.respondWith(new Response(
XLSX.write(wb, {type:"buffer", bookType:"xlsx"}),
{
status: 200,
headers: {
"Content-Type": "application/vnd.ms-excel",
"Content-Disposition": 'attachment; filename="SheetJSDeno.xlsx"'
}
}
));
}
/* standard Deno web server */
const server = Deno.listen({ port: 7262 });
console.log(`HTTP webserver running. Access it at: http://localhost:7262/`);
for await (const conn of server) doNotAwaitThis(conn);
Bun 响应预计为 Response 对象。具有 buffer 类型的 XLSX.write 返回可在 Response 构造函数中使用的 Buffer 对象。
¥Bun responses are expected to be Response objects. XLSX.write with buffer
type returns Buffer objects that can be used in the Response constructor.
/* generate Buffer */
const buf = XLSX.write(wb, { type:"buffer", bookType:"xlsx" });
/* return Response */
return new Response(buf, {
headers: {
"Content-Type": "application/vnd.ms-excel",
"Content-Disposition": 'attachment; filename="SheetJSBun.xlsx"'
}
});
Complete Example (click to show)
Download xlsx.mjs.
Save the following script to bun.js and run with bun bun.js. Open a web
browser and access http://localhost:7262/ to download the exported workbook.
import * as XLSX from "./xlsx.mjs";
/* 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");
export default {
port: 7262,
fetch(request) {
/* generate Buffer */
const buf = XLSX.write(wb, {type:"buffer", bookType:"xlsx"});
/* return Response */
return new Response(buf, {
headers: {
"Content-Type": "application/vnd.ms-excel",
"Content-Disposition": 'attachment; filename="SheetJSBun.xlsx"'
}
});
},
};
示例:远程文件
¥Example: Remote File
此示例重点介绍使用 XMLHttpRequest 和 fetch 等 API 以及第三方库上传文件(浏览器用语中的 "Ajax")。
¥This example focuses on uploading files ("Ajax" in browser parlance) using APIs
like XMLHttpRequest and fetch as well as third-party libraries.
- Browser
- NodeJS
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);
XLSX.write 和 type: "buffer" 将生成一个 NodeJS Buffer,它可以与标准 NodeJS 方法一起使用来上传数据。
¥XLSX.write with type: "buffer" will generate a NodeJS Buffer which can be
used with standard NodeJS approaches for uploading data.
NodeJS 从 18.0 版开始发布,原生支持 fetch:
¥NodeJS releases starting from version 18.0 have native support for fetch:
const XLSX = require("xlsx");
async function upload_wb(workbook, url, name="test.xlsx", field="file") {
const buf = XLSX.write(workbook, { bookType: "xlsx", type: "buffer" });
const blob = new Blob([buf], {type:"application/octet-stream"});
const body = new FormData();
body.append(field, blob, name);
/* perform POST request */
return fetch(url, { method: 'POST', body });
}
生成 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
- Vanilla JS
- React
- VueJS
x-spreadsheet 是一个交互式数据网格,用于在网络浏览器中预览和修改结构化数据。
¥x-spreadsheet is an interactive data grid for
previewing and modifying structured data in the web browser.
react-data-grid 是为 React 构建的数据网格。它使用两个属性:数据对象的 rows 和描述列的 columns。网格 API 可以很好地处理数组数组。
¥react-data-grid is a data grid built for
React. It uses two properties: rows of data objects and columns which
describe the columns. The grid API can play nice with an array of arrays.
该演示首先获取远程文件并使用 XLSX.read 进行提取:
¥This demo starts by fetching a remote file and using XLSX.read to extract:
import { useEffect, useState } from "react";
import DataGrid from "react-data-grid";
import { read, utils } from "xlsx";
import 'react-data-grid/lib/styles.css';
const url = "https://xlsx.nodejs.cn/pres.xlsx";
export default function App() {
const [columns, setColumns] = useState([]);
const [rows, setRows] = useState([]);
useEffect(() => {(async () => {
const wb = read(await (await fetch(url)).arrayBuffer());
/* use sheet_to_json with header: 1 to generate an array of arrays */
const data = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]], { header: 1 });
/* see react-data-grid docs to understand the shape of the expected data */
setColumns(data[0].map((r) => ({ key: r, name: r })));
setRows(data.slice(1).map((r) => r.reduce((acc, x, i) => {
acc[data[0][i]] = x;
return acc;
}, {})));
})(); });
return <DataGrid columns={columns} rows={rows} />;
}
vue3-table-lite 是 VueJS 3 数据表。
¥vue3-table-lite is a VueJS 3 data table.
示例:数据加载
¥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 colspan 和 rowspan 属性进行序列化。
¥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:
- Vanilla JS
- React
- VueJS
此示例分配 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>
通常建议使用 React 友好的工作流程,但可以生成 HTML 并在 React 中使用 dangerouslySetInnerHTML:
¥It is generally recommended to use a React-friendly workflow, but it is possible
to generate HTML and use it in React with dangerouslySetInnerHTML:
import * as XLSX from 'xlsx';
function Tabeller(props) {
/* the workbook object is the state */
const [workbook, setWorkbook] = React.useState(XLSX.utils.book_new());
/* fetch and update the workbook with an effect */
React.useEffect(() => { (async() => {
/* fetch and parse workbook -- see the fetch example for details */
setWorkbook(XLSX.read(await (await fetch("sheetjs.xlsx")).arrayBuffer()));
})(); }, []);
return workbook.SheetNames.map(name => ( <>
<h3>name</h3>
<div dangerouslySetInnerHTML={{
/* this __html mantra is needed to set the inner HTML */
__html: XLSX.utils.sheet_to_html(workbook.Sheets[name])
}} />
</> ));
}
react 演示 包含更多 React 示例。
¥The react demo includes more React examples.
通常建议使用 VueJS 友好的工作流程,但可以生成 HTML 并通过 v-html 指令在 VueJS 中使用它:
¥It is generally recommended to use a VueJS-friendly workflow, but it is possible
to generate HTML and use it in VueJS with the v-html directive:
import { read, utils } from 'xlsx';
import { reactive } from 'vue';
const S5SComponent = {
mounted() { (async() => {
/* fetch and parse workbook -- see the fetch example for details */
const workbook = read(await (await fetch("sheetjs.xlsx")).arrayBuffer());
/* loop through the worksheet names in order */
workbook.SheetNames.forEach(name => {
/* generate HTML from the corresponding worksheets */
const html = utils.sheet_to_html(workbook.Sheets[name]);
/* add to state */
this.wb.wb.push({ name, html });
});
})(); },
/* this state mantra is required for array updates to work */
setup() { return { wb: reactive({ wb: [] }) }; },
template: `
<div v-for="ws in wb.wb" :key="ws.name">
<h3>{{ ws.name }}</h3>
<div v-html="ws.html"></div>
</div>`
};
vuejs 演示 包含更多 React 示例。
¥The vuejs demo includes more React examples.
生成单个工作表快照
¥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_csv是XLSX.utils.sheet_to_csv的流式版本。¥
XLSX.stream.to_csvis the streaming version ofXLSX.utils.sheet_to_csv. -
XLSX.stream.to_html是XLSX.utils.sheet_to_html的流式版本。¥
XLSX.stream.to_htmlis the streaming version ofXLSX.utils.sheet_to_html. -
XLSX.stream.to_json是XLSX.utils.sheet_to_json的流式版本。¥
XLSX.stream.to_jsonis the streaming version ofXLSX.utils.sheet_to_json. -
XLSX.stream.to_xlml是流式 SpreadsheetML2003 工作簿编写器。¥
XLSX.stream.to_xlmlis the streaming SpreadsheetML2003 workbook writer.
"流导出" 更详细地描述了该功能。
¥"Stream Export" describes the function in more detail.