首页 > 解决方案 > 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看起来像这样 在此处输入图像描述

当我使用这样的循环插入行值时,如何管理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);
}  

标签: javascripttypescript

解决方案


如果您有标题 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)
    }  

如您所见,我们必须知道 JSON 的“键”是什么,为了动态创建它们,我们获取对象的键并循环它们,并创建我们想要的 csv 格式。

工作 JsFiddle https://jsfiddle.net/36o8cryu/


推荐阅读