尝试使用javascript将我的Array值保存为CSV文件列。现在我的代码按行保存数组值。
电流输出 -
必需的输出 -
到目前为止我的代码 -
<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));
});
我之前尝试过使用各种功能但是没有成功。有没有办法实现所需的输出。任何帮助将不胜感激。
答案 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));