gpt4 book ai didi

javascript - 如何使用 NodeJS 将 2 个 XLSX 文件合并为一个

转载 作者:行者123 更新时间:2023-12-03 04:04:00 25 4
gpt4 key购买 nike

我目前正在使用 NodeJS 生成 XLSX 电子表格。我正在使用 xlsx-populate 模块在 Express 服务器上创建单页 XLSX 文件。

我想知道是否有人知道一种使用 Node 将多个 XLSX 文件合并为一个包含多个工作表的文件的方法。

谢谢!

示例:

const xlsx = require('xlsx-populate');

xlsx.fromFileAsync('template1.xlsx')
.then((workbook) => {
// populate the workbook with stuff

return workbook.toFileAsync('spreadsheet1.xlsx');
})
.then(() => xlsx.fromFileAsync('template2.xlsx'))
.then((workbook) => {
// populate the other workbook with stuff

return workbook.toFileAsync('spreadsheet2.xlsx');
});

此 Promise 链保存两个单独的 XLSX 文件(spreadsheet1.xlsx、spreadsheet2.xlsx),每个文件都是根据相应的模板文件构建的。 xlsx-populate 不允许您从同一工作簿上的不同 XLSX 文件创建多个工作表,因此我想知道是否可以将两个工作簿合并为一个包含多个工作表的工作簿?

编辑

我最终将模块切换到 excel4node,我发现这是一个更灵活但更复杂的模块。我的问题是我有两个模板文件,每个模板文件都包含一个图像,我想使用 xlsx-populate 合并到一个文件中。

由于我未能找到一种使用 xlsx-populate 将两个模板合并到一个文件的成功方法,因此我使用 excel4node 从头开始​​重建模板文件,插入图像(xlsx-populate 不支持)。

最佳答案

此代码片段可以将两个 Excel 文件合并为一个新文件。

 const XlsxPopulate = require('xlsx-populate');

Promise.all([
XlsxPopulate.fromFileAsync('./src/data/template.xlsx'),
XlsxPopulate.fromFileAsync('./src/data/template2.xlsx')
])
.then(workbooks => {
const workbook = workbooks[0];
const workbook2 = workbooks[1];
const sheets2 = workbook2.sheets();

sheets2.forEach(sheet => {
const newSheet = workbook.addSheet(sheet.name());
const usedRange = sheet.usedRange();
const oldValues = usedRange.value();

newSheet.range(usedRange.address()).value(oldValues);
});

return workbook.toFileAsync('./src/data/xlsx-populate/spreadsheet2.xlsx');
});

已知问题:

会丢失第二个的样式,因为复制样式功能正在开发中,请引用here .

关于javascript - 如何使用 NodeJS 将 2 个 XLSX 文件合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44641258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com