Here is the code which generates a CSV from array, Hard coded values gives proper column Headings and data in rows. I am adding data using a loop but unable to understand how do I add column headings.
Here is the hard coded array to export csv
var Results = [
["Col1", "Col2", "Col3", "Col4"],
["Data", 50, 100, 500],
["Data", -100, 20, 100],
];
exportToCsv = function() {
var CsvString = "";
Results.forEach(function(RowItem, RowIndex) {
RowItem.forEach(function(ColItem, ColIndex) {
CsvString += ColItem + ',';
});
CsvString += "\r\n";
});
CsvString = "data:application/csv," + encodeURIComponent(CsvString);
var x = document.createElement("A");
x.setAttribute("href", CsvString );
x.setAttribute("download","somedata.csv");
document.body.appendChild(x);
x.click();
}
<button onclick="exportToCsv()">export to CSV</button>
How do I manage col1 , col2 , col3 when I am inserting row values using a loop like this -
for(let i=0;i<this.goalList.length;i++)
{
console.log(i,this.goalList)
var Result = [
[this.goalList[i]['name'],this.goalList[i]['desc'], this.goalList[i]['phno']]
];
Results.push(Result);
}
