![](/img/trans.png)
[英]Not able to get right Sheets from huge xlsx files — using NodeJS XLSX library
[英]How to combine 2 XLSX files into one using NodeJS
我目前正在使用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,sheetsheet2.xlsx),每個文件都是從相應的模板文件構建的。 xlsx-populate不允許您從同一工作簿上的不同XLSX文件創建多個工作表,所以我想知道是否可以將兩個工作簿合並為一個包含多個工作表的工作表?
編輯
我最終將模塊切換到excel4node,我發現它是一個更靈活但更復雜的模塊。 我的問題是我有兩個模板文件,每個文件都包含一個圖像,我想使用xlsx-populate合並為一個文件。
由於無法找到使用xlsx-populate將兩個模板合並到一個文件的成功方法,因此我使用excel4node從頭開始重建模板文件,並插入圖像(xlsx-populate不支持)。
將新工作表添加到工作簿
本示例使用XLSX.utils.aoa_to_sheet制作工作表並將新工作表追加到工作簿:
var new_ws_name = "SheetJS";
/* make worksheet */
var ws_data = [
[ "S", "h", "e", "e", "t", "J", "S" ],
[ 1 , 2 , 3 , 4 , 5 ]
];
var ws = XLSX.utils.aoa_to_sheet(ws_data);
/* Add the sheet name to the list */
wb.SheetNames.push(ws_name);
/* Load the worksheet object */
wb.Sheets[ws_name] = ws;
此代碼段可以將兩個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');
});
已知問題:
它將失去第二種樣式,因為復制樣式功能正在開發中,請參閱此處 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.