【发布时间】:2022-12-04 18:23:01
【问题描述】:
在 NodeJs 中创建和传输包含数百万行的大数据的 excel 文件。 我尝试在互联网上搜索,但实际上找不到任何好的指导。非常感谢你的回复。
【问题讨论】:
标签: node.js
在 NodeJs 中创建和传输包含数百万行的大数据的 excel 文件。 我尝试在互联网上搜索,但实际上找不到任何好的指导。非常感谢你的回复。
【问题讨论】:
标签: node.js
使用 xlsx 包,这是一种在 Node.js 中创建和操作 Excel 文件的简单方法。 xlsx 包支持流式传输,它允许您创建大型 Excel 文件而不会耗尽内存。
const XLSX = require('xlsx');
const fs = require('fs');
// Define the data for the Excel file
const data = [
['ID', 'Name', 'Email'],
['1', 'John Doe', 'john.doe@example.com'],
['2', 'Jane Doe', 'jane.doe@example.com'],
// Add more rows here...
];
// Create a new workbook and add worksheet
const workbook = XLSX.utils.book_new();
const worksheet = XLSX.utils.aoa_to_sheet(data);
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
// Create a write stream for the Excel file
const stream = fs.createWriteStream('myfile.xlsx');
// Use the write stream to write the Excel file to disk
XLSX.write(workbook, {type: 'stream', bookType: 'xlsx'}, stream)
.then(() => {
// The file has been written successfully
console.log('File written successfully');
})
.catch(err => {
// There was an error writing the file
console.error(err);
});
导入 xlsx 包并使用 fs 模块为 Excel 文件创建写入流。然后将 Excel 文件的数据定义为数组的数组 (AOA),并使用该数据创建新的工作簿和工作表。
然后使用 XLSX.write 方法将 Excel 文件写入写入流,使用 bookType: 'xlsx' 选项指定文件应以 XLSX 格式写入。 XLSX.write 方法返回一个承诺,因此您可以使用 then 和 catch 方法分别处理成功和失败的情况。更改文件名和路径,它将在您的磁盘中。
【讨论】: