本地文件访问
读取和写入文件需要原生平台支持。
¥Reading from and writing to files requires native platform support.
SheetJS readFile
和 writeFile
方法包括对某些平台的支持。由于沙箱和安全设置的原因,readFile
无法在 Web 浏览器中运行,并且不保证 writeFile
在所有情况下都能运行。
¥SheetJS readFile
and writeFile
methods include support for some platforms.
Due to sandboxing and security settings, readFile
does not work in the web
browser and writeFile
is not guaranteed to work in all cases.
该演示着眼于各种用于读取和写入文件的 Web API。我们将探讨如何在 SheetJS 函数和各种 API 之间传递数据。
¥This demo looks at various web APIs for reading and writing files. We'll explore how to pass data between SheetJS functions and various APIs.
"常见用例" 部分中还提供了一些片段:
¥Some snippets are also available in the "Common Use Cases" section:
其他演示涵盖了特殊平台上本地文件访问的 API:
¥Other demos cover APIs for local file access on special platforms:
-
"iOS 和 Android 应用" 涵盖移动应用框架
¥"iOS and Android Apps" covers mobile app frameworks
-
"桌面应用" 涵盖桌面应用
¥"Desktop Apps" covers desktop apps
-
"命令行工具" 涵盖独立命令行工具
¥"Command-Line Tools" covers standalone command-line tools
二进制数据
¥Binary Data
JavaScript 引擎以多种结构表示二进制数据。
¥JavaScript engines represent binary data in a number of structures.
SheetJS read
function[^1] 的 type
选项控制如何解释数据。该参数区分 二进制字符串 和 Base64 字符串。
¥The type
option for SheetJS read
function[^1] controls how the data should
be interpreted. This parameter distinguishes binary strings
from Base64 strings.
SheetJS write
函数 [^2] 的 type
选项控制输出存储。
¥The type
option for SheetJS write
function[^2] controls the output storage.
Uint8Array
和 Buffer
¥Uint8Array
and Buffer
Uint8Array
是类型化数组,其中每个值都是 8 位无符号整数。包括 NodeJS 在内的服务器端平台通常使用 Uint8Array
或子类(例如 Buffer
[^3])来表示文件中的数据。
¥A Uint8Array
is a Typed Array where each value is a 8-bit unsigned integer.
Server-side platforms including NodeJS typically use Uint8Array
, or a subclass
such as Buffer
[^3], to represent data from files.
SheetJS read
方法可以从 Uint8Array
读取数据,无需任何选项:
¥The SheetJS read
method can read data from Uint8Array
without any options:
const wb = XLSX.read(u8);
SheetJS write
方法可以使用选项 type: "buffer"
生成存储在 Uint8Array
结构中的工作簿:
¥The SheetJS write
method can generate workbooks stored in
Uint8Array
structures with the option type: "buffer"
:
const u8 = XLSX.write(wb, {bookType: "xlsx", type: "buffer"});
在 NodeJS 中,write
方法将生成一个 Buffer
实例。
¥In NodeJS, the write
method will generate a Buffer
instance.
ArrayBuffer
ArrayBuffer
表示字节数组。Uint8Array
构造函数可以同步创建视图,而无需复制底层数据:
¥An ArrayBuffer
represents an array of bytes. The Uint8Array
constructor can
synchronously create a view without copying the underlying data:
/* create a Uint8Array "view" */
const u8 = new Uint8Array(array_buffer);
SheetJS read
方法可以从 ArrayBuffer
读取数据,无需特殊选项,因为它执行上述转换。SheetJS write
方法可以使用选项 type: "array"
生成存储在 ArrayBuffer
结构中的工作簿
¥The SheetJS read
method can read data from ArrayBuffer
without special
options, as it performs the aforementioned conversion. The SheetJS write
method can generate workbooks stored in ArrayBuffer
structures with the
option type: "array"
Blob
和 File
¥Blob
and File
Blob
是一个不透明的数据指针。数据无法立即访问。
¥Blob
is an opaque pointer to data. The data is not immediately accessible.
File
扩展了 Blob
,支持存储文件名和其他元数据。
¥File
extends Blob
with support for storing file names and other metadata.
SheetJS read
方法不处理 Blob
或 File
。解析之前必须将底层数据拉入 ArrayBuffer
。有两种方法:
¥The SheetJS read
method does not handle Blob
or File
. The underlying data
must be pulled into an ArrayBuffer
before parsing. There are two approaches:
A) 现代浏览器支持 arrayBuffer
方法。它返回一个解析为 ArrayBuffer
的 promise:
¥A) Modern browsers support the arrayBuffer
method. It returns a promise that
resolves to ArrayBuffer
:
// usage: const wb = await blob_to_wb(blob);
async function blob_to_wb(blob) {
const ab = await blob.arrayBuffer(); // pull data from Blob
return XLSX.read(ab); // parse ArrayBuffer
}
B) 为了获得更广泛的浏览器支持,FileReader
API 可以使用 readAsArrayBuffer
方法拉取 ArrayBuffer
数据:
¥B) For broader browser support, the FileReader
API can pull ArrayBuffer
data
using the readAsArrayBuffer
method:
// usage: file_to_wb(file, function(wb) { /* wb is a workbook object */ });
function file_to_wb(file, callback) {
var reader = new FileReader();
reader.onload = function(e) {
/* e.target.result is an ArrayBuffer */
callback(XLSX.read(e.target.result));
};
reader.readAsArrayBuffer(file);
}
FileReaderSync in Web Workers (click to show)
FileReaderSync
is only available in Web Workers. It returns an ArrayBuffer
:
// assuming main thread called worker.postMessage({ file: file_object })
self.addEventListener('message', (e) => {
/* get file object from message */
var file = e.data.file;
/* Read file data */
const ab = new FileReaderSync().readAsArrayBuffer(file);
/* Parse file */
const wb = XLSX.read(ab);
/* DO SOMETHING WITH wb HERE */
});
"User-Submitted File" example includes a live demo.
SheetJS write
方法可以生成 Uint8Array
,可以将其传递给 Blob
构造函数:
¥The SheetJS write
method can generate a Uint8Array
which can be passed to
the Blob
constructor:
function wb_to_blob(wb, bookType) {
/* write workbook to Uint8Array */
const u8 = XLSX.write(wb, { bookType: bookType || "xlsx", type: "buffer" });
/* create array of parts */
const parts = [ u8 ]; // `Blob` constructor expects this
/* create Blob */
const blob = new Blob(parts, { type: "application/vnd.ms-excel" });
return blob;
}
File
构造函数接受额外的 name
参数:
¥The File
constructor accepts an additional name
argument:
function wb_to_file(wb, filename) {
/* impute bookType from file extension */
const ext = filename.slice(filename.lastIndexOf(".") + 1);
/* write workbook to Uint8Array */
const u8 = XLSX.write(wb, { bookType: ext, type: "buffer" });
/* create array of parts */
const parts = [ u8 ]; // `File` constructor expects this
/* create File */
const file = new File(parts, filename, { type: "application/vnd.ms-excel" });
return file;
}
二进制字符串
¥Binary Strings
二进制字符串是每个字符代码在 0
和 255
之间的字符串。该结构是根据 FileReader#readAsBinaryString
方法生成的。
¥Binary strings are strings where each character code is between 0
and 255
.
This structure is generated from the FileReader#readAsBinaryString
method.
SheetJS read
方法支持带有 type: "binary"
的二进制字符串。以下代码片段显示了 readAsBinaryString
如何与 SheetJS 配对:
¥The SheetJS read
method supports binary strings with type: "binary"
. The
following snippet shows how readAsBinaryString
can be paired with SheetJS:
// usage: file_bs_to_wb(file, function(wb) { /* wb is a workbook object */ });
function file_bs_to_wb(file, callback) {
var reader = new FileReader();
reader.onload = function(e) {
/* e.target.result is a binary string */
callback(XLSX.read(e.target.result, { type: "binary" }));
};
reader.readAsBinaryString(file);
}
SheetJS write
方法可以使用 type: "binary"
生成二进制字符串:
¥The SheetJS write
method can generate binary strings using type: "binary"
:
/* write workbook to binary string */
const bstr = XLSX.write(wb, { bookType: "xlsx", type: "binary" });
Base64 字符串
¥Base64 Strings
Base64 字符串使用 64 个显示 ASCII 字符进行编码。该结构是根据 btoa
、FileReader#readAsDataURL
方法以及移动和桌面应用框架中的许多平台 API 生成的。
¥Base64 strings are encoded using 64 display ASCII characters. This structure is
generated from btoa
, the FileReader#readAsDataURL
method, and many platform
APIs in mobile and desktop app frameworks.
SheetJS read
方法支持带有 type: "base64"
的 Base64 字符串。以下代码片段显示了 readAsDataURL
如何与 SheetJS 配对:
¥The SheetJS read
method supports Base64 strings with type: "base64"
. The
following snippet shows how readAsDataURL
can be paired with SheetJS:
// usage: file_b64_to_wb(file, function(wb) { /* wb is a workbook object */ });
function file_b64_to_wb(file, callback) {
var reader = new FileReader();
reader.onload = function(e) {
/* e.target.result is a base64 string */
callback(XLSX.read(e.target.result, { type: "base64" }));
};
reader.readAsDataURL(file);
}
SheetJS write
方法可以使用 type: "base64"
生成 Base64 字符串:
¥The SheetJS write
method can generate Base64 strings using type: "base64"
:
/* write workbook to Base64 string */
const b64 = XLSX.write(wb, { bookType: "xlsx", type: "base64" });
数字数组
¥Arrays of Numbers
某些平台将二进制数据表示为数字数组,其中每个数字代表文件中的一个字节。
¥Some platforms represent binary data as arrays of numbers, where each number represents one byte in the file.
SheetJS read
方法支持无符号字节数组(其中每个值在 0
和 255
之间)和 type: "array"
。
¥The SheetJS read
method supports arrays of unsigned bytes (where each value
is between 0
and 255
) with type: "array"
.
谷歌表格 遵循 Java 签名数据类型约定。字节数组包括从 -128
到 127
的值。
¥Google Sheets follows Java signed data type
conventions. Byte arrays include values from -128
to 127
.
How to Fix Signed Arrays (click to show)
The unsigned value for a negative byte can be calculated with a bitwise AND
(&
) operation against 0xFF
:
const unsigned_byte = signed_byte & 0xFF;
For legacy platforms including NetSuite 2.0, the
bitwise AND assignment operator (&=
) can rectify an array in place:
/* convert a signed byte array to an unsigned byte array in place */
for(var i = 0; i < array.length; ++i) array[i] &= 0xFF;
For modern platforms, the Uint8Array
constructor understands signed bytes:
/* copy data into a new Uint8Array */
const u8 = new Uint8Array(array);
网络浏览器
¥Web Browsers
并非所有浏览器都支持所有 Web API。例如,Firefox 不支持 "文件系统访问 API"。
¥Not all web APIs are supported in all browsers. For example, Firefox does not support the "File System Access API".
即使浏览器在技术上支持 Web API,它也可能在客户端浏览器中被禁用。有些 API 不提供任何反馈。
¥Even when a browser technically supports a web API, it may be disabled in the client browser. Some APIs do not give any feedback.
在非安全 (HTTP) 上下文中,Google Chrome 默认会阻止下载。以下屏幕截图是在 Chrome 126.0.6478.127 中拍摄的:
¥In insecure (HTTP) contexts, Google Chrome will block downloads by default. The following screenshot was taken in Chrome 126.0.6478.127:
这是一个浏览器限制,没有纯 JavaScript 库可以解决此问题。有关更多详细信息,请参阅 SheetJS 错误跟踪器中的 问题 #3145。
¥This is a browser limitation and no pure JavaScript library can work around the issue. See Issue #3145 in the SheetJS bug tracker for more details.
HTML5 下载属性
¥HTML5 Download Attribute
写入文件
¥Writing Files
writeFile
将尝试使用该属性在浏览器中下载。
¥writeFile
will attempt a download in the browser using the attribute.
XLSX.writeFile(wb, "SheetJS.xlsx");
Implementation Details (click to show)
Under the hood, it creates a special URL and clicks a link. The library method includes a few workarounds for legacy browsers
XLSX.writeFile(wb, "SheetJS.xlsx");
is roughly equivalent to:
/* write data -- `writeFile` infers bookType from filename but `write` cannot */
const u8 = XLSX.write(wb, { bookType: "xlsx", type: "buffer" });
/* create Blob */
const blob = new Blob([u8]);
/* create object URL */
const url = URL.createObjectURL(blob);
/* create `A` DOM element */
const a = document.createElement("a");
/* set export file name */
a.download = "SheetJS.xlsx";
/* wire up the object URL to the DOM element */
a.href = url;
/* add to the page */
document.body.appendChild(a);
/* click the link */
a.click();
/* remove the element from the page */
document.body.removeChild(a);
XLSX.writeFile
需要 DOM 访问,并且无法在 Web Worker 中工作!
¥XLSX.writeFile
requires DOM access and will not work in a Web Worker!
解决方法是从 Worker 生成文件数据(使用 XLSX.write
)并将数据发送回主上下文以进行实际下载操作。
¥The workaround is to generate the file data from the Worker (using XLSX.write
)
and send the data back to the main context for the actual download action.
"创建本地文件" 包括在线演示。
¥"Creating a Local File" includes a live demo.
谷歌标签管理器
¥Google Tag Manager
众所周知,Google 跟踪代码管理器会拦截和损坏链接。此问题将表现为 UUID 文件名,例如 01234567-89ab-cdef-0123-456789abcdef
。
¥Google Tag Manager is known to intercept and corrupt links. This issue will
manifest as UUID file names like 01234567-89ab-cdef-0123-456789abcdef
.
对于使用 GTM 的站点,建议修补 document.createElement
并在执行导出后恢复。
¥For sites using GTM, it is recommended to patch document.createElement
and
revert after performing the export.
GTM Workaround (click to show)
The workaround is to ensure new A
elements created by document.createElement
have the target
attribute set to _blank
.
After calling writeFile
, the old version of the method should be restored.
/* preparation */
document.createElement2 = document.createElement;
document.createElement = function(...args) {
if(args.length == 1 && args[0].toLowerCase() == "a") {
const a = document.createElement2("a");
a.target = "_blank";
return a;
}
return document.createElement2.call(this, ...args);
};
/* export (XLSX.writeFile) */
XLSX.writeFile(wb, "SheetJS.xlsx");
/* cleanup */
setTimeout(() => {
document.createElement = document.createElement2;
delete document.createElement2;
}, 1000);
文件接口
¥File API
读取文件
¥Reading Files
在 <input type="file">
的 change
事件中,事件对象将具有 target
属性。target
的 files
属性是 File
对象的列表。
¥In the change
event of <input type="file">
, the event object will have a
target
property. The files
property of target
is a list of File
objects.
async function handleFileAsync(e) {
/* get first file */
const file = e.target.files[0];
/* get raw data */
const data = await file.arrayBuffer();
/* data is an ArrayBuffer */
const workbook = XLSX.read(data);
/* do something with the workbook here */
console.log(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]));
}
input_dom_element.addEventListener("change", handleFileAsync, false);
HTML 拖放 API
¥HTML Drag and Drop API
读取文件
¥Reading Files
drop
事件的 dataTransfer
属性包含 File
对象的列表:
¥The dataTransfer
property of the drop
event holds a list of File
objects:
/* suppress default behavior for drag and drop events */
function suppress(e) { e.stopPropagation(); e.preventDefault(); }
/* handle data from drop event */
async function handleDropAsync(e) {
suppress(e);
/* get first file */
const f = e.dataTransfer.files[0];
/* get raw data */
const data = await f.arrayBuffer();
/* data is an ArrayBuffer */
const wb = XLSX.read(data);
/* do something with the workbook here */
console.log(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]));
}
drop_dom_element.addEventListener("drop", handleDropAsync, false);
drop_dom_element.addEventListener("dragover", suppress, false);
drop_dom_element.addEventListener("dragenter", suppress, false);
文件系统访问 API
¥File System Access API
在撰写本文时,浏览器支持相当有限。Chrome 在版本 86 中引入了该功能。Safari 不支持文件系统访问 API。
¥At the time of writing, browser support was fairly limited. Chrome introduced the feature in version 86. Safari did not support File System Access API.
文件系统访问 API 仅在安全 (HTTPS) 上下文中可用。[^4]
¥The File System Access API is only available in secure (HTTPS) contexts.[^4]
上次测试此演示时,Google Chrome 并未将条目添加到 "下载" 列表中。尽管如此,实际文件写入正确。
¥When this demo was last tested, Google Chrome did not add an entry to the "Downloads" list. Nevertheless the actual file was written correctly.
该浏览器演示在以下环境中进行了测试:
¥This browser demo was tested in the following environments:
浏览器 | 日期 |
---|---|
Chrome 122 | 2024-04-07 |
一些较少使用的浏览器不支持文件系统访问 API:
¥Some lesser-used browsers do not support File System Access API:
浏览器 | 日期 |
---|---|
Safari 17.4 | 2024-04-07 |
火狐 124 | 2024-04-07 |
Live Example (click to show)
This live example reads a file then tries to save as XLSX. If the File System Access API is not supported, the result will be a clear message.
function SheetJSRoundTripFileSystemAPI() { return window.showSaveFilePicker ? ( <button onClick={async () => { /* Show picker and get data */ const [rFile] = await window.showOpenFilePicker({ types: [{ description: 'Spreadsheets', accept: { 'application/vnd.ms-excel': ['.xlsx', '.xls', '.xlsb', /*...*/] } }], excludeAcceptAllOption: true, multiple: false }); const ab = await (await rFile.getFile()).arrayBuffer(); /* parse */ const wb = XLSX.read(ab); /* Show picker and get handle to file */ const wFile = await window.showSaveFilePicker({ suggestedName: "SheetJSRT.xlsx", types: [ { description: 'XLSX', accept: { 'application/vnd.ms-excel': ['.xlsx'] } } ] }); const wstream = await wFile.createWritable(); /* write */ const buf = XLSX.write(wb, { bookType: "xlsx", type: "buffer" }); wstream.write(buf); /* close stream to commit file */ wstream.close(); }}>Click to read then save as XLSX</button> ) : ( <b>This browser does not support File System Access API</b> ); }
读取文件
¥Reading Files
window.showOpenFilePicker
显示文件选择器并解析为文件句柄数组。当设置 multiple: false
时,数组只有一个元素。
¥window.showOpenFilePicker
shows a file picker and resolves to an array of
file handles. When multiple: false
is set, the array has one element.
getFile
方法解析为 File
对象,可以使用 arrayBuffer
方法读取其数据:
¥The getFile
method resolves to a File
object whose data can be read with
the arrayBuffer
method:
/* Show picker and get data */
const [hFile] = await window.showOpenFilePicker({
types: [{
description: 'Spreadsheets',
accept: { 'application/vnd.ms-excel': ['.xlsx', '.xls', '.xlsb', /*...*/] }
}],
excludeAcceptAllOption: true,
multiple: false
});
const ab = await (await hFile.getFile()).arrayBuffer();
/* parse */
const wb = XLSX.read(ab);
/* do something with the workbook */
console.log(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]));
写入文件
¥Writing Files
window.showSaveFilePicker
显示文件选择器并解析为文件句柄。createWritable
方法解析为 FileSystemWritableFileStream
,它很容易接受来自 XLSX.write
的 Uint8Array
数据:
¥window.showSaveFilePicker
shows a file picker and resolves to a file handle.
The createWritable
method resolves to a FileSystemWritableFileStream
, which
readily accepts Uint8Array
data from XLSX.write
:
/* Show picker and get handle to file */
const hFile = await window.showSaveFilePicker({
suggestedName: "SheetJS.xlsx",
types: [
{ description: 'Excel 2007+ (XLSX)', accept: { 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx'] } },
{ description: 'Excel 97-2004 (XLS)', accept: { 'application/vnd.ms-excel': ['.xls'] } },
{ description: 'Excel 2007+ Binary (XLSB)', accept: { 'application/vnd.ms-excel.sheet.binary.macroEnabled.12': ['.xlsb'] } },
/* note that each MIME type must be unique! */
]
});
const wstream = await hFile.createWritable();
/* get extension */
const ext = hFile.name.slice(hFile.name.lastIndexOf(".")+1)
/* write */
wstream.write(XLSX.write(wb, { bookType: ext, type: "buffer" }))
/* close stream to commit file */
wstream.close();
文件和目录条目 API
¥File and Directory Entries API
在 Web 浏览器中,文件和目录条目 API 已被弃用,不建议用于新应用。
¥In the web browser, the File and Directory Entries API has been deprecated and is not recommended for new applications.
cordova-plugin-file
仍然使用 API 模式。
¥cordova-plugin-file
still uses the API patterns.
写入文件
¥Writing Files
API 是基于回调的。高层次上:
¥The API is callback-based. At a high level:
-
window.requestFileSystem
请求访问文件系统。回调接收FileSystem
对象。¥
window.requestFileSystem
requests access to the filesystem. The callback receives aFileSystem
object. -
使用
getFile
方法创建文件。回调接收表示文件的FileSystemFileEntry
对象。¥A file is created using the
getFile
method. The callback receives aFileSystemFileEntry
object representing the file. -
使用文件对象的
createWriter
方法创建写入器。回调接收一个FileWriter
对象,表示用于写入的文件句柄。¥A writer is created using the
createWriter
method of the file object. The callback receives aFileWriter
object representing a file handle for writing. -
使用
FileWriter
对象的write
方法写入数据。与其他方法不同,回调直接附加到FileWriter
对象。¥Data is written using the
write
method of theFileWriter
object. Unlike the other methods, callbacks are attached to theFileWriter
object directly.
// Request File System Access
window.requestFileSystem(window.PERSISTENT, 0, (fs) => {
// Request a handle to "SheetJS.xlsx", making a new file if necessary
fs.root.getFile("SheetJS.xlsx", {create: true}, entry => {
// Request a FileWriter for writing data
entry.createWriter(writer => {
// The FileWriter API needs an actual Blob
const u8 = XLSX.write(wb, { type: "buffer", bookType: "xlsx" });
const data = new Blob([u8], { type: "application/vnd.ms-excel" });
// `onwriteend` is called on success, `onerror` called on error
writer.onwriteend = () => {}; writer.onerror = () => {};
// write the data
writer.write(data);
});
});
});
IE 浏览器
¥Internet Explorer
Internet Explorer 提供了 Chromium 未采用的专有 API。
¥Internet Explorer offered proprietary APIs that were not adopted by Chromium.
Blob API
写入文件
¥Writing Files
IE10 和 IE11 支持 navigator.msSaveBlob
。如果可用,XLSX.writeFile
将使用此方法。
¥IE10 and IE11 support navigator.msSaveBlob
. XLSX.writeFile
will use this
method if it is available.
Implementation Details (click to show)
XLSX.writeFile(wb, "SheetJS.xlsx");
is roughly equivalent to:
/* write data -- `writeFile` infers bookType from filename but `write` cannot */
const u8 = XLSX.write(wb, { bookType: "xlsx", type: "buffer" });
/* create Blob */
const blob = new Blob([u8]);
/* call msSaveBlob */
navigator.msSaveBlob(blob, "SheetJS.xlsx");
VB 脚本
¥VBScript
读写文件
¥Reading and Writing Files
支持 VBScript 的 Internet Explorer 6-9 Scripting.FileSystemObject
。现代浏览器不支持此功能。
¥Internet Explorer 6-9 with VBScript support Scripting.FileSystemObject
. This
is not supported in modern browsers.
该方法在库 readFile
和 writeFile
方法中实现。它要求在主库脚本之前加载填充脚本:
¥This approach is implemented in the library readFile
and writeFile
methods.
It requires the shim script to be loaded before the main library script:
<!-- load the shim script first -->
<script src="shim.min.js"></script>
<!-- then load the main script -->
<script src="xlsx.full.min.js"></script>
其他平台
¥Other Platforms
NodeJS
fs.readFileSync
和 fs.writeFileSync
允许读取和写入文件。
¥fs.readFileSync
and fs.writeFileSync
allow for reading and writing files.
使用 require
时,readFile
和 writeFile
支持这些:
¥When using require
, these are supported in readFile
and writeFile
:
var XLSX = require("xlsx");
var wb = XLSX.readFile("sheetjs.numbers");
XLSX.writeFile(wb, "sheetjs.xls");
安装 对于与 NodeJS ECMAScript 模块一起使用有一个特殊说明:
¥Installation has a special note for use with NodeJS ECMAScript Modules:
import { readFile, writeFile, set_fs } from 'xlsx';
import * as fs from 'fs';
set_fs(fs);
var wb = readFile("sheetjs.numbers");
writeFile(wb, "sheetjs.xlsx");
Implementation Details (click to show)
XLSX.readFile(filepath)
is equivalent to:
CommonJS
var fs = require("fs");
var buf = fs.readFileSync(filepath);
var wb = XLSX.read(buf);
ECMAScript Modules
import { read } from "xlsx";
import { readFileSync } from "fs";
var buf = readFileSync(filepath);
var wb = read(buf);
XLSX.writeFile(wb, filepath)
is equivalent to:
CommonJS
var fs = require("fs"), path = require("path");
var buf = XLSX.write(wb, { bookType: path.extname(filepath).slice(1), type: "buffer" });
fs.writeFileSync(filepath, buf);
ECMAScript Modules
import { write } from "xlsx";
import { writeFileSync } from "fs";
import { extname } from "path";
var buf = write(wb, { bookType: extname(filepath).slice(1), type: "buffer" });
writeFileSync(filepath, buf);
ExtendScript
在 Photoshop 和其他 Adobe 应用中,readFile
和 writeFile
在底层使用 File
对象:
¥In Photoshop and other Adobe apps, readFile
and writeFile
use the File
object under the hood:
#include "xlsx.extendscript.js"
var wb = XLSX.readFile("sheetjs.xlsx");
XLSX.writeFile(wb, "sheetjs.csv");
扩展脚本演示 还涵盖 "通用扩展平台" (CEP) 和 "统一的可扩展平台" (UXP) 详细信息。
¥The ExtendScript demo also covers "Common Extensibility Platform" (CEP) and "Unified Extensibility Platform" (UXP) details.
Chrome 扩展程序
¥Chrome Extensions
在 Manifest v2 Chrome 扩展中,writeFile
调用 chrome.downloads.download
。
¥In Manifest v2 Chrome extensions, writeFile
calls chrome.downloads.download
.
此方法使用 URL.createObjectURL
,这是 Manifest v3 后台服务工作线程不支持的 API。对于小型导出,可以生成并下载原始 Base64 URL。
¥This approach uses URL.createObjectURL
, an API that is not supported in a
Manifest v3 Background Service Worker. For small exports, raw Base64 URLs can be
generated and downloaded.
Chromium 演示 涵盖了细节。
¥The Chromium demo covers the details.
Deno
readFile
使用 Deno.readFileSync
,writeFile
使用 Deno.writeFileSync
:
¥readFile
uses Deno.readFileSync
and writeFile
uses Deno.writeFileSync
:
// @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.WorkBook = XLSX.readFile("sheetjs.numbers");
XLSX.writeFile(wb, "sheetjs.xlsx");
任何使用 XLSX.readFile
的 Deno 脚本都需要 --allow-read
权利。
¥Any Deno script using XLSX.readFile
requires the --allow-read
entitlement.
任何使用 XLSX.writeFile
的 Deno 脚本都需要 --allow-write
权利。
¥Any Deno script using XLSX.writeFile
requires the --allow-write
entitlement.
Implementation Details (click to show)
XLSX.readFile(filepath)
is equivalent to:
ECMAScript Modules
// @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 u8: Uint8Array = Deno.readFileSync(filepath);
const wb: XLSX.WorkBook = XLSX.read(u8);
XLSX.writeFile(wb, filepath)
is equivalent to:
ECMAScript Modules
// @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 u8 = XLSX.write(wb, { bookType: filepath.slice(filepath.lastIndexOf(".")+1), type: "buffer" });
Deno.writeFileSync(filepath, u8);
Bun
Bun 需要 fs
模块:
¥Bun requires the fs
module:
import { readFile, writeFile, set_fs } from 'xlsx';
import * as fs from 'fs';
set_fs(fs);
var wb = readFile("sheetjs.numbers");
writeFile(wb, "sheetjs.xlsx");
实现与 NodeJS ECMAScript 模块 相同。
¥The implementation is identical to NodeJS ECMAScript Modules.
应用
¥Apps
桌面和移动应用都有自己的特定 API,在单独的演示中进行了介绍:
¥Desktop and mobile apps have their own specific APIs covered in separate demos:
[^1]: 见 "输入类型" 于 "读取文件"
¥See "Input Type" in "Reading Files"
[^2]: 见 "写入文件" 中的 "支持的输出格式" 类型
¥See "Supported Output Formats" type in "Writing Files"
[^3]: 请参阅 NodeJS 文档中的 "缓冲区和 TypedArray"。
¥See "Buffers and TypedArrays" in the NodeJS documentation.
[^4]: 详细信息请参见 问题 3145 SheetJS 错误跟踪器。特别感谢 @sjoenH
!
¥See issue 3145 in the SheetJS bug tracker for more details. Special thanks to @sjoenH
!