0

I want to create Excel file that consist of 2 arrays of data with ExcelJS.

I can create the Excel file:

var Excel = require('exceljs');
var workbook = new Excel.Workbook();
var sheet = workbook.addWorksheet('My Sheet', {properties:{tabColor:{argb:'FFC0000'}}});

I can add column headers:

sheet.columns = [{key:"date", header:"Date"}, {key: "quantity", header: "Quantity"}]

I got 2 arrays for these columns:

array_date = [2018-01-04, 2018-01-06, 2018-01-08, 2018-01-09]
array_quantity = [25, 32, 54, 48]

I want to combine these 2 arrays to one array like this:

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}];

If I can combine, I able to add as row for every data:

for(i in merged){
  sheet.addRow(merged[i]);
}

Then I can create the Excel File:

workbook.xlsx.writeFile("some.xlsx").then(function() {
console.log("xls file is written.");
});

How can I combine two arrays to one If they are ordered? Also, I'm wondering is this the best approach to create excel file in NodeJS?

1

2 Answers 2

5

You can create the new array with

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],
}));
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.