我有 Excel 文件,每个文件的大小最大可达 150mb。我需要逐步加载该文件的块(例如,批量加载 1000 行),以便我可以将它们转换为 JSON 并操作它们。
我尝试使用 XLSX 库,它在流读取方面没有提供太多支持。我也尝试过 ExcelJS,但我发现总是包含类似的内容:
const workbook = new ExcelJS.Workbook();
await workbook.xlsx.readFile(inputFilePath);
所以它总是回到使用 XLSX 的 readFile() 并且我得到一个大小错误。
我还尝试使用 Gnumeric 将 Excel 文件转换为 CSV 以尝试以这种方式读取它,但它也引发了大小错误。
我还尝试使用node-excel-stream包中的ExcelReader,但它不灵活,因为我需要定义Excel文件中每个工作表的架构,而我并不总是拥有这些信息,而且我的Excel文件有时有一个标题行中存在空字符串 '',我想为每个空标题指定一个不同的值(例如 __EMPTY_CELL_01 等),以便以正确的格式输出我的 JSON 对象。
无论我往哪里看,这似乎都是一个死胡同,它开始让我沮丧:((我是我工作中的实习生,我的主管对 NodeJS 没有太多经验)。
有谁知道可以帮助我吗?
要在 Node.js 中的流中加载内存中的大型 Excel 文件,可以考虑以下方法:
这是一个示例代码片段,演示如何使用流读取 Excel 文件
const fs = require('fs');
const ExcelJS = require('exceljs');
// Create a read stream for the Excel file
const readStream = fs.createReadStream('path/to/your/large/excel/file.xlsx');
// Create a new workbook instance
const workbook = new ExcelJS.Workbook();
// Read the Excel file in streams
readStream
.pipe(workbook.xlsx.createReadStream())
.on('data', (data) => {
// Process each chunk of data here
// Convert to JSON, manipulate, etc.
})
.on('end', () => {
// Finalize processing when the stream ends
})
.on('error', (error) => {
// Handle any errors that occur during the stream
});
此代码为 Excel 文件设置一个读取流,并通过
exceljs
库的读取流方法将其传输。当数据以块的形式读取时,您可以根据需要处理每个块。确保将 'path/to/your/large/excel/file.xlsx'
替换为 Excel 文件的实际路径。
请记住在运行此代码之前安装必要的 Node.js 包(
exceljs
、fs
等)。另外,根据您的具体要求调整错误处理和数据处理。