1

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>

Excel looks like this enter image description here

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

2 Answers 2

1

In case you have as headers Col1,Col2,Col3;

function downloadCsv(){
var rows= [{'col1':10,'col2':10,'col3':10},{'col1':10,'col2':10,'col3':10}, 
    {'col1':10,'col2':10,'col3':10},{'col1':10,'col2':10,'col3':10}]
    var headers = "col1,col2,col3\n";
    rows.forEach((row)=>{
      var values = []
      Object.keys(row).forEach((key)=>{        
        if(Array.isArray(row[key])){
          var type = [];
          row[key].forEach(element => {
            type.push(element.name)
          });
          console.log(type)
          values.push("\"" + type.join() + "\"")
        }else{
          typeof(row[key]) == "string" ? values.push("\"" + row[key] + "\"") : (row[key] == null ? values.push("") : values.push(row[key].toString()))
        }
      });
      headers = headers + values.join(",") + "\n"
      
    })
      download('CSV', 'Payroll.csv', 'text/csv', headers)
    }  

As you can see we have to know what are the "keys" of our JSON, in order to create them dynamically, we obtain the keys of the object and we loop them, and create the format of the csv that we want.

Working JsFiddle https://jsfiddle.net/36o8cryu/

Sign up to request clarification or add additional context in comments.

1 Comment

I achieve adding 1 line after the for loop Results.unshift(["Name", "Desc", "Phone", "Address"]); , it worked, accepting your working answer, thanks for the help
0

You can initialise your Results array to contain the headings.

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.