使用Javascript

时间:2017-09-30 20:01:08

标签: javascript arrays csv export-to-csv

尝试使用javascript将我的Array值保存为CSV文件列。现在我的代码按行保存数组值。

电流输出 -

  • COUNTRY1,COUNTRY2,COUNTRY3,country4
  • capital1,capital2,capital3,capital4,
  • CURRENCY1,currency2,currency3,currency4

必需的输出 -

  • COUNTRY1,capital1,CURRENCY1
  • COUNTRY2,capital2,currency2
  • COUNTRY3,capital3,currency3
  • country4,capital4,currency4

到目前为止我的代码 -

<form>
    <input id="download" type="button" value="Download">
</form>

function downloadableCSV(rows) {
  var content = "data:text/csv;charset=utf-8,";

  rows.forEach(function(column, index) {
   content = content + column.join(",") + "\n";
  });

  return encodeURI(content);
}

var country = ["England","Australia","Mexico","Brazil","Spain","Portugal","Italy","Thailand","Japan"];
var capital = ["London","Canberra","Mexico City","Brasilia","Madrid","Lisbon","Rome","Bangkok","Tokyo"];
var currency = ["Pound","Dollar","peso","Brazilian real","Euro","Euro","Euro","Thai baht","Japanese yen"];
var continent = ["Europe","Australia","NorthAmerica","SouthAmerica","Europe","Europe","Europe","Asia","Asia"];
var language = ["English","English","Spanish","Portuguese","Spainish","Portuguese","Italian","Thailand","Japanese"];
var heading =  ["Country","Capital","currency","continent","language"];

var rows = [[heading],[country],[capital],[currency],[continent],[language]];

$("#download").click(function() {
  window.open(downloadableCSV(rows));
});

我之前尝试过使用各种功能但是没有成功。有没有办法实现所需的输出。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

要对数据进行分组,您可以使用lodash(https://lodash.com/docs/4.17.4#zip)中的zip

这是工作js代码(https://jsbin.com/ditodosime/edit?html,js,output):

function downloadableCSV(heading, rows) {
  var content = "data:text/csv;charset=utf-8,";

  var dataRows = rows.map(function(columnValues, index) {
    return columnValues.join(",");
  });

  content += heading + "\n" + dataRows.join("\n");

  return encodeURI(content);
}

var country = ["England","Australia","Mexico","Brazil","Spain","Portugal","Italy","Thailand","Japan"];
var capital = ["London","Canberra","Mexico City","Brasilia","Madrid","Lisbon","Rome","Bangkok","Tokyo"];
var currency = ["Pound","Dollar","peso","Brazilian real","Euro","Euro","Euro","Thai baht","Japanese yen"];
var continent = ["Europe","Australia","NorthAmerica","SouthAmerica","Europe","Europe","Europe","Asia","Asia"];
var language = ["English","English","Spanish","Portuguese","Spainish","Portuguese","Italian","Thailand","Japanese"];
var heading =  ["Country","Capital","currency","continent","language"];

var rows = _.zip(country,capital,currency,continent,language);

window.open(downloadableCSV(heading,  rows));