0

我想用 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 文件的最佳方法吗?

4

2 回答 2

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],
}));
于 2018-01-17T08:15:20.390 回答
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);
于 2018-01-17T08:16:07.267 回答