Js数组转CSV添加列标题

这是CSV从数组生成一个代码,硬编码值给出正确的列标题和行中的数据。我正在使用循环添加数据,但无法理解如何添加列标题。


这是导出 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 看起来像这样

http://img4.mukewang.com/6389be610001434013670766.jpg

当我使用这样的循环插入行值时,如何管理col1 、 col2 、 col3 -


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

}  


达令说
浏览 130回答 2
2回答

萧十郎

如果您有标题 Col1、Col2、Col3;function downloadCsv(){var rows= [{'col1':10,'col2':10,'col3':10},{'col1':10,'col2':10,'col3':10},&nbsp;&nbsp; &nbsp; {'col1':10,'col2':10,'col3':10},{'col1':10,'col2':10,'col3':10}]&nbsp; &nbsp; var headers = "col1,col2,col3\n";&nbsp; &nbsp; rows.forEach((row)=>{&nbsp; &nbsp; &nbsp; var values = []&nbsp; &nbsp; &nbsp; Object.keys(row).forEach((key)=>{&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if(Array.isArray(row[key])){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var type = [];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row[key].forEach(element => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type.push(element.name)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(type)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; values.push("\"" + type.join() + "\"")&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; typeof(row[key]) == "string" ? values.push("\"" + row[key] + "\"") : (row[key] == null ? values.push("") : values.push(row[key].toString()))&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; headers = headers + values.join(",") + "\n"&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; download('CSV', 'Payroll.csv', 'text/csv', headers)&nbsp; &nbsp; }&nbsp;&nbsp;如您所见,我们必须知道我们的 JSON 的“键”是什么,为了动态创建它们,我们获取对象的键并循环它们,并创建我们想要的 csv 格式。工作 JsFiddle https://jsfiddle.net/36o8cryu/

跃然一笑

您可以初始化Results数组以包含标题。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript