我想用ExcelJS创建包含2个数据数组的Excel文件。
我可以创建Excel文件:
var Excel = require('exceljs');
var workbook = new Excel.Workbook();
var sheet = workbook.addWorksheet('My Sheet', {properties:{tabColor:{argb:'FFC0000'}}});
我可以添加列标题:
sheet.columns = [{key:"date", header:"Date"}, {key: "quantity", header: "Quantity"}]
我为这些列添加了2个数组:
array_date = [2018-01-04, 2018-01-06, 2018-01-08, 2018-01-09]
array_quantity = [25, 32, 54, 48]
我想将这两个数组合并为一个这样的数组:
var merged = [{date:"2018-01-04", quantity:25}
, {date:"2018-01-06", quantity:32}
, {date:"2018-01-08", quantity:42}
, {date:"2018-01-09", quantity:48}];
如果我可以合并,我可以为每个数据添加行:
for(i in merged){
sheet.addRow(merged[i]);
}
然后我可以创建Excel文件:
workbook.xlsx.writeFile("some.xlsx").then(function() {
console.log("xls file is written.");
});
如何将两个数组合并为一个如果订购它们?另外,我想知道这是在NodeJS中创建excel文件的最佳方法吗?
答案 0 :(得分:5)
您可以使用
创建新数组var array_date = ["2018-01-04", "2018-01-06", "2018-01-08", "2018-01-09"];
var array_quantity = [25, 32, 54, 48];
var merged = array_date.map((date, i) => ({
date,
quantity: array_quantity[i],
}));
答案 1 :(得分:1)
array_date = [2018-01-04, 2018-01-06, 2018-01-08, 2018-01-09]
array_quantity = [25, 32, 54, 48]
var merged=[];
for(var i=0;i<array_date.length;i++){
merged.push({date:array_date[i], quantity:array_quantity[i]});
}
console.log(merged);