Data Export数据导出
Writing Workbooks编写工作簿
API
Generate spreadsheet bytes (file) from data从数据生成电子表格字节(文件)
vardata=XLSX.write(workbook,opts);
The write method attempts to package data from the workbook into a file in memory. write方法尝试将工作簿中的数据打包到内存中的文件中。By default, XLSX files are generated, but that can be controlled with the 默认情况下,会生成XLSX文件,但这可以通过opts参数的bookType property of the opts argument. bookType属性进行控制。Based on the 根据type option, the data can be stored as a "binary string", JS string, Uint8Array or Buffer.type选项,数据可以存储为“二进制字符串”、JS字符串、Uint8Array或缓冲区。
The second 第二个opts argument is required. opts参数是必需的。"Writing Options"“写入选项” covers the supported properties and behaviors.涵盖支持的属性和行为。
Generate and attempt to save file生成并尝试保存文件
XLSX.writeFile(workbook,filename,opts);
The writeFile method packages the data and attempts to save the new file. writeFile方法打包数据并尝试保存新文件。The export file format is determined by the extension of 导出文件格式由filename (SheetJS.xlsx signals XLSX export, SheetJS.xlsb signals XLSB export, etc).filename的扩展名决定(SheetJS.xlsx信号XLSX导出、SheetJS.xlsb信号XLSB导出等)。
The second 第二个opts argument is optional. opts参数是可选的。"Writing Options"“写入选项” covers the supported properties and behaviors.涵盖支持的属性和行为。
Generate and attempt to save an XLSX file生成并尝试保存XLSX文件
XLSX.writeFileXLSX(workbook,filename,opts);
The writeFile method embeds a number of different export functions. writeFile方法嵌入了许多不同的导出函数。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.当只需要XLSX导出时,此方法避免引用其他导出函数。
The second 第二个opts argument is optional. opts参数是可选的。"Writing Options"“写入选项” covers the supported properties and behaviors.涵盖支持的属性和行为。
note
The writeFile and writeFileXLSX methods uses platform-specific APIs to save files. writeFile和writeFileXLSX方法使用特定于平台的API来保存文件。The APIs do not generally provide feedback on whether files were created.API通常不提供是否创建了文件的反馈。
Examples
Here are a few common scenarios (click on each subtitle to see the code).以下是一些常见的场景(单击每个子标题以查看代码)。
The demos cover special deployments in more detail.演示更详细地介绍了特殊部署。
Example: Local File示例:本地文件
XLSX.writeFile supports writing local files in platforms like NodeJS. 支持在Node.js等平台中编写本地文件。In other platforms like React Native, 在其他平台(如React Native)中,应使用文件数据调用XLSX.write should be called with file data.XLSX.write。
- Browser
- NodeJS
- Deno
- Electron
- React Native
- Photoshop
- Headless
XLSX.writeFile wraps a few techniques for triggering a file save:总结了触发文件保存的几种技术:
URLbrowser API creates an object URL for the file, which the library uses by creating a link and forcing a click.浏览器API为文件创建对象URL,库通过创建链接并强制单击来使用该URL。It is supported in modern browsers.现代浏览器支持它。msSaveBlobis an IE10+ API for triggering a file save.是用于触发文件保存的IE10+API。IE_FileSaveuses VBScript and ActiveX to write a file in IE6+ for Windows XP and Windows 7.使用VBScript和ActiveX在适用于Windows XP和Windows 7的IE6+中编写文件。The shim must be included in the containing HTML page.填充程序必须包含在包含HTML的页面中。
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 */
SWF workaround for Windows 95+Windows 95的SWF解决方案+ (click to show)
warning警告
Each moving part in this solution has been deprecated years ago:多年前,此解决方案中的每个移动部件都已被弃用:
Adobe stopped supporting Flash Player at the end of 20202020年底,Adobe停止支持Flash PlayerMicrosoft stopped supporting IE8 in 2019 and stopped supporting IE9 in 20202019年,微软停止支持IE8,2020年,微软停止支持IE9Downloadifysupport ended in 2010 and支持结束于2010年,SWFObjectsupport ended in 2016SWFObject支持结束于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. 这些技术适用于大多数现代浏览器和旧的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:使用Flash SWF按钮生成本地文件,适用于ActiveX不可用的环境:
Downloadify.create(id,{
/* other options are required! read the downloadify docs for more info */
filename:"test.xlsx",
data:function(){returnXLSX.write(wb,{bookType:"xlsx",type:"base64"});},
append:false,
dataType:"base64"
});
The oldie demo shows an IE-compatible fallback scenario.oldie演示展示了一个与IE兼容的回退场景。
writeFile uses 在引擎盖下使用fs.writeFileSync under the hood:fs.writeFileSync:
varXLSX=require("xlsx");
/* output format determined by filename */
XLSX.writeFile(workbook,"out.xlsb");
For Node ESM, 对于节点ESM,必须手动加载fs must be loaded manually:fs:
import*asfsfrom"fs";
import{writeFile,set_fs}from"xlsx/xlsx.mjs";
set_fs(fs);
/* output format determined by filename */
writeFile(workbook,"out.xlsb");
writeFile uses 在引擎盖下使用Deno.writeFileSync under the hood:Deno.writeFileSync:
// @deno-types="https://cdn.sheetjs.com/xlsx-0.18.9/package/types/index.d.ts"
import*asXLSXfrom'https://cdn.sheetjs.com/xlsx-0.18.9/package/xlsx.mjs';
XLSX.writeFile(workbook,"test.xlsx");
Applications writing files must be invoked with the 写入文件的应用程序必须使用--allow-write flag. --allow-write标志调用。The deno demo has more examplesdeno演示有更多示例
writeFile can be used in the renderer process:可以在渲染器过程中使用:
/* From the renderer process */
varXLSX=require("xlsx");
XLSX.writeFile(workbook,"out.xlsb");
Electron APIs have changed over time. 随着时间的推移,Electron API发生了变化。 The electron demo shows a complete example and details the required version-specific settings.electron演示展示了一个完整的示例,并详细介绍了所需的特定于版本的设置。
caution
React Native does not provide a way to write files to the filesystem. React Native不提供将文件写入文件系统的方法。A separate third-party library must be used.必须使用单独的第三方库。
Since React Native internals change between releases, libraries may only work with specific versions of React Native. 由于React本机内部在不同版本之间会发生变化,因此库只能与React本机的特定版本一起工作。Project documentation should be consulted before picking a library.在选择库之前,应查阅项目文档。
The react demo includes a sample React Native app.react演示包括一个示例react Native应用程序。
The following libraries have been tested:以下库已经过测试:
The base64 encoding returns strings compatible with the base64 type:base64编码返回与base64类型兼容的字符串:
import*asXLSXfrom"xlsx";
import{Dirs,FileSystem}from"react-native-file-access";
constDDP=Dirs.DocumentDir+"/";
constb64=XLSX.write(workbook,{type:'base64',bookType:"xlsx"});
/* b64 is a base64 string */
awaitFileSystem.writeFile(DDP+"sheetjs.xlsx",b64,"base64");
The ascii encoding accepts binary strings compatible with the binary type:ascii编码接受与binary类型兼容的二进制字符串:
import*asXLSXfrom"xlsx";
import{writeFile,DocumentDirectoryPath}from"react-native-fs";
constDDP=DocumentDirectoryPath+"/";
constbstr=XLSX.write(workbook,{type:'binary',bookType:"xlsx"});
/* bstr is a binary string */
awaitwriteFile(DDP+"sheetjs.xlsx",bstr,"ascii");
writeFile wraps the 在Photoshop和其他ExtendScript目标中包装File logic in Photoshop and other ExtendScript targets. File逻辑。The specified path should be an absolute path:指定的路径应为绝对路径:
#include"xlsx.extendscript.js"
/* Ask user to select path */
varthisFile=File.saveDialog("Select an output file","*.xlsx;*.xls");
/* output format determined by filename */
XLSX.writeFile(workbook,thisFile.absoluteURI);
The extendscript demo includes a more complex example.extendscript演示包括一个更复杂的示例。
PhantomJS (Headless Webkit) File GenerationPhantomJS(无头Webkit)文件生成 (click to show)
The headless demo includes a complete demo to convert HTML files to XLSB workbooks using PhantomJS. headless演示包括使用PhantomJS将HTML文件转换为XLSB工作簿的完整演示。PhantomJS PhantomJS fs.write supports writing files from the main process but has a different interface from the NodeJS fs module:fs.write支持从主进程写入文件,但与Node.js fs模块具有不同的接口:
varXLSX=require('xlsx');
varfs=require('fs');
/* generate a binary string */
varbin=XLSX.write(workbook,{type:"binary",bookType:"xlsx"});
/* write to file */
fs.write("test.xlsx",bin,"wb");
Note: The section "Processing HTML Tables" shows how to generate a workbook from HTML tables in a page in "Headless WebKit".注意:“处理HTML表格”一节介绍了如何从“无标题WebKit”页面中的HTML表格生成工作簿。
Example: Remote File示例:远程文件
This example focuses on uploading files ("Ajax" in browser parlance) using APIs like 本例重点介绍使用XMLHttpRequest and fetch as well as third-party libraries.XMLHttpRequest和fetch等API以及第三方库上载文件(用浏览器的说法是“Ajax”)。
- Browser
- NodeJS
caution
Some platforms like Azure and AWS will attempt to parse POST request bodies as UTF-8 strings before user code can see the data. 一些平台,如Azure和AWS,将尝试在用户代码可以看到数据之前,将POST请求主体解析为UTF-8字符串。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.有一些解决方法,但最安全的方法是调整服务器进程或Lambda函数以接受Base64字符串。
A complete example using XHR is included in the XHR demo, along with examples for fetch and wrapper libraries. XHR演示中包含了使用XHR的完整示例,以及获取和包装库的示例。This example assumes the server can handle Base64-encoded files (see the demo for a basic nodejs server):本例假设服务器可以处理Base64编码的文件(请参阅基本Node.js服务器的演示):
/* in this example, send a base64 string to the server */
varwbout=XLSX.write(workbook,{bookType:"xlsx",type:"base64"});
/* prepare data for POST */
varformdata=newFormData();
formdata.append("file","test.xlsx");// <-- server expects `file` to hold name
formdata.append("data",wbout);// <-- `data` holds the base64-encoded data
/* perform POST request */
varreq=newXMLHttpRequest();
req.open("POST","/upload",true);
req.send(formdata);
For servers that do not parse POST request bodies as UTF-8 strings, a 对于不将POST请求正文解析为UTF-8字符串的服务器,可以从Blob can be generated from the array output:array输出生成Blob:
/* in this example, send a Blob to the server */
varwbout=XLSX.write(workbook,{bookType:"xlsx",type:"array"});
/* prepare data for POST */
varblob=newBlob([newUint8Array(wbout)],{type:"application/octet-stream"});
varformdata=newFormData();
formdata.append("file",blob,"test.xlsx");
/* perform POST request */
fetch("/upload",{method:'POST',body:formdata});
XLSX.write with type: "buffer" will generate a NodeJS Buffer which can be used with standard NodeJS approaches for uploading data.type: "buffer"的XLSX.write将生成一个Node.jsBuffer,该缓冲区可与标准Node.js方法一起用于上传数据。
Node 17.5 and 18.0 have native support for fetch:Node17.5和18.0原生支持fetch:
constXLSX=require("xlsx");
constbuf=XLSX.write(workbook,{bookType:"xlsx",type:"buffer"});
varblob=newBlob([buf],{type:"application/octet-stream"});
varformdata=newFormData();
formdata.append("file",blob,"test.xlsx");
/* perform POST request */
fetch("https://thisis.a.test/upload",{method:'POST',body:formdata});
Generating JSON and JS Data生成JSON和JS数据
JSON and JS data tend to represent single worksheets. JSON和JS数据往往表示单个工作表。The utility functions in this section work with single worksheets.本节中的实用程序功能适用于单个工作表。
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.是一个对象,其键为工作表名称,其值为工作表对象。
The "first worksheet" is stored at “第一张工作表”存储在workbook.Sheets[workbook.SheetNames[0]].workbook.Sheets[workbook.SheetNames[0]]中。
API
Create an array of JS objects from a worksheet从工作表创建JS对象数组
varjsa=XLSX.utils.sheet_to_json(worksheet,opts);
Create an array of arrays of JS values from a worksheet从工作表中创建JS值数组
varaoa=XLSX.utils.sheet_to_json(worksheet,{...opts,header:1});
The sheet_to_json utility function walks a workbook in row-major order, generating an array of objects. sheet_to_json实用程序函数按行主顺序遍历工作簿,生成一个对象数组。The second 第二个参数opts argument controls a number of export decisions including the type of values (JS values or formatted text). opts控制许多导出决策,包括值的类型(JS值或格式化文本)。The "JSON" section describes the argument in more detail.“JSON”部分更详细地描述了参数。
By default, 默认情况下,sheet_to_json scans the first row and uses the values as headers. sheet_to_json扫描第一行,并将值用作标题。With the 使用header: 1 option, the function exports an array of arrays of values.header:1选项,该函数导出值数组。
Examples示例
Example: Data Grids示例:数据网格
- Vanilla JS
- React
- VueJS
x-spreadsheet is an interactive data grid for previewing and modifying structured data in the web browser. 是一种交互式数据网格,用于在web浏览器中预览和修改结构化数据。The demo includes a sample script with the 演示包括一个带有stox function for converting from a workbook to x-spreadsheet. stox函数的示例脚本,用于将工作簿转换为x-spreadsheet。Live Demo: 现场演示:https://oss.sheetjs.com/sheetjs/x-spreadsheet
react-data-grid is a data grid built for React. 是为React构建的数据网格。It uses two properties: 它使用两个属性:数据对象的rows of data objects and columns which describe the columns. rows和描述列的columns。 For the purposes of massaging the data to fit the 为了调整数据以适应react-data-grid API it is easiest to start from an array of arrays.react-data-gridAPI,最容易从数组开始。
This demo starts by fetching a remote file and using 本演示首先获取一个远程文件,并使用XLSX.read to extract:XLSX.read提取:
import{useEffect,useState}from"react";
importDataGridfrom"react-data-grid";
import{read,utils}from"xlsx";
consturl="https://oss.sheetjs.com/test_files/RkNumber.xls";
exportdefaultfunctionApp(){
const[columns,setColumns]=useState([]);
const[rows,setRows]=useState([]);
useEffect(()=>{(async()=>{
constwb=read(await(awaitfetch(url)).arrayBuffer());
/* use sheet_to_json with header: 1 to generate an array of arrays */
constdata=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;
returnacc;
},{})));
})();});
return<DataGridcolumns={columns}rows={rows}/>;
}
vue3-table-lite is a simple VueJS 3 data table. 是一个简单的VueJS 3数据表。 It is featured in the VueJS demo.
Example: Data Loading示例:数据加载
Populating a database (SQL or no-SQL)填充数据库(SQL或无SQL) (click to show)
The database demo includes examples of working with databases and query results.database演示包括使用数据库和查询结果的示例。
Numerical Computations with TensorFlow.jsTensorFlowjs的数值计算 (click to show)
@tensorflow/tfjs and other libraries expect data in simple arrays, well-suited for worksheets where each column is a data vector. 其他库希望数据以简单数组形式存在,非常适合于每列都是数据向量的工作表。 That is the transpose of how most people use spreadsheets, where each row is a vector.这是大多数人使用电子表格方式的转换,其中每一行都是一个向量。
A single 单个Array#map can pull individual named rows from sheet_to_json export:Array#map可以将单个命名行从sheet_to_json导出:
constXLSX=require("xlsx");
consttf=require('@tensorflow/tfjs');
constkey="age";// this is the field we want to pull
constages=XLSX.utils.sheet_to_json(worksheet).map(r=>r[key]);
consttf_data=tf.tensor1d(ages);
All fields can be processed at once using a transpose of the 2D tensor generated with the 所有字段都可以使用sheet_to_json export with header: 1. sheet_to_json配合header: 1导出生成的2D张量转置立即处理。The first row, if it contains header labels, should be removed with a slice:如果第一行包含标题标签,则应使用切片删除:
constXLSX=require("xlsx");
consttf=require('@tensorflow/tfjs');
/* array of arrays of the data starting on the second row */
constaoa=XLSX.utils.sheet_to_json(worksheet,{header:1}).slice(1);
/* dataset in the "correct orientation" */
consttf_dataset=tf.tensor2d(aoa).transpose();
/* pull out each dataset with a slice */
consttf_field0=tf_dataset.slice([0,0],[1,tensor.shape[1]]).flatten();
consttf_field1=tf_dataset.slice([1,0],[1,tensor.shape[1]]).flatten();
The array demo shows a complete example.array演示展示了一个完整的示例。
Generating HTML Tables生成HTML表
API
Generate HTML Table from Worksheet从工作表生成HTML表
varhtml=XLSX.utils.sheet_to_html(worksheet);
The sheet_to_html utility function generates HTML code based on the worksheet data. sheet_to_html实用程序函数根据工作表数据生成html代码。Each cell in the worksheet is mapped to a 工作表中的每个单元格都映射到一个<TD> element. <TD>元素。Merged cells in the worksheet are serialized by setting 工作表中的合并单元格通过设置colspan and rowspan attributes.colspan和rowspan属性进行序列化。
Examples示例
The sheet_to_html utility function generates HTML code that can be added to any DOM element by setting the innerHTML:sheet_to_html实用程序函数生成html代码,可以通过设置innerHTML将其添加到任何DOM元素:
varcontainer=document.getElementById("tavolo");
container.innerHTML=XLSX.utils.sheet_to_html(worksheet);
Combining with 结合fetch, constructing a site from a workbook is straightforward:fetch,从工作簿构建站点非常简单:
- Vanilla JS
- React
- VueJS
This example assigns the 本例分配DIV元素的innerHTML of a DIV element:innerHTML:
<body>
<style>TABLE{border-collapse:collapse;}TD{border:1pxsolid;}</style>
<divid="tavolo"></div>
<scriptsrc="https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min.js"></script>
<scripttype="text/javascript">
(async()=>{
/* fetch and parse workbook -- see the fetch example for details */
constworkbook=XLSX.read(await(awaitfetch("sheetjs.xlsx")).arrayBuffer());
letoutput=[];
/* loop through the worksheet names in order */
workbook.SheetNames.forEach(name=>{
/* generate HTML from the corresponding worksheets */
constworksheet=workbook.Sheets[name];
consthtml=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>
It is generally recommended to use a React-friendly workflow, but it is possible to generate HTML and use it in React with 通常建议使用React友好的工作流,但也可以生成HTML并将其用于React使用dangerouslySetInnerHTML:dangerouslySetInnerHTML:
import*asXLSXfrom'xlsx';
functionTabeller(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 */
constwb=XLSX.read(await(awaitfetch("sheetjs.xlsx")).arrayBuffer());
setWorkbook(wb);
})();});
returnworkbook.SheetNames.map(name=>(<>
<h3>name</h3>
<divdangerouslySetInnerHTML={{
/* this __html mantra is needed to set the inner HTML */
__html:XLSX.utils.sheet_to_html(workbook.Sheets[name])
}}/>
</>));
}
The react demo includes more React examples.react演示包括更多的react示例。
It is generally recommended to use a VueJS-friendly workflow, but it is possible to generate HTML and use it in VueJS with the 通常建议使用VueJS友好的工作流,但也可以生成HTML并在VueJS中使用v-html directive:v-HTML指令:
import{read,utils}from'xlsx';
import{reactive}from'vue';
constS5SComponent={
mounted(){(async()=>{
/* fetch and parse workbook -- see the fetch example for details */
constworkbook=read(await(awaitfetch("sheetjs.xlsx")).arrayBuffer());
/* loop through the worksheet names in order */
workbook.SheetNames.forEach(name=>{
/* generate HTML from the corresponding worksheets */
consthtml=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>`
};
The vuejs demo includes more React examples.vuejs演示包含更多的React示例。
Generating Single-Worksheet Snapshots生成单个工作表快照
The sheet_to_* functions accept a worksheet object.sheet_to_*函数接受工作表对象。
API
Generate a CSV from a single worksheet从单个工作表生成CSV
varcsv=XLSX.utils.sheet_to_csv(worksheet,opts);
This snapshot is designed to replicate the "CSV UTF8 (此快照旨在复制“CSV UTF8(.csv)" output type. .csv)”输出类型。"Delimiter-Separated Output"“分隔符分隔的输出” describes the function and the optional 更详细地描述了函数和可选opts argument in more detail.opts参数。
Generate "Text" from a single worksheet从单个工作表生成“文本”
vartxt=XLSX.utils.sheet_to_txt(worksheet,opts);
This snapshot is designed to replicate the "UTF16 Text (此快照旨在复制“UTF16文本(.txt)" output type. .txt)”输出类型。"Delimiter-Separated Output"“分隔符分隔的输出” describes the function and the optional 更详细地描述了函数和可选opts argument in more detail.opts参数。
Generate a list of formulae from a single worksheet从单个工作表生成公式列表
varfmla=XLSX.utils.sheet_to_formulae(worksheet);
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. range=formula的形式呈现,而普通单元格以cell=formula or value的形式呈现。String literals are prefixed with an apostrophe 字符串文字的前缀为撇号', consistent with Excel's formula bar display.',与Excel的公式栏显示一致。
"Formulae Output"“公式输出” describes the function in more detail.更详细地描述了该功能。
Streaming Write流式写入
The streaming write functions are available in the XLSX.stream object. XLSX.stream对象中提供了流写入功能。They take the same arguments as the normal write functions but return a NodeJS Readable Stream.它们采用与普通写函数相同的参数,但返回Node.js可读流。
XLSX.stream.to_csvis the streaming version of是XLSX.utils.sheet_to_csv.XLSX.utils.sheet_to_csv的流式版本。XLSX.stream.to_htmlis the streaming version of是XLSX.utils.sheet_to_html.XLSX.utils.sheet_to_html的流式版本。XLSX.stream.to_jsonis the streaming version of是XLSX.utils.sheet_to_json.XLSX.utils.sheet_to_json的流式版本。
nodejs convert to CSV and write fileNode.js转换为CSV并写入文件 (click to show)
varoutput_file_name="out.csv";
varstream=XLSX.stream.to_csv(worksheet);
stream.pipe(fs.createWriteStream(output_file_name));
nodejs write JSON stream to screenNode.js将JSON流写入屏幕 (click to show)
/* to_json returns an object-mode stream */
varstream=XLSX.stream.to_json(worksheet,{raw:true});
/* the following stream converts JS objects to text via JSON.stringify */
varconv=newTransform({writableObjectMode:true});
conv._transform=function(obj,e,cb){cb(null,JSON.stringify(obj)+"\n");};
stream.pipe(conv);conv.pipe(process.stdout);
https://github.com/sheetjs/sheetaki pipes write streams to nodejs response.管道将流写入Node.js响应。