这是我的代码:
<script type="text/javascript">
functionExport(json_data, "User_Report", true);
function functionExport(JSONData, ReportTitle, ShowLabel) {
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
if (ShowLabel) {
var row = "";
for (var index in arrData[0]) {
row += index.toUpperCase() + ',';
}
row = row.slice(0, -1);
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
for (var index in arrData[i]) {
row += '"' + $('<div>').html(arrData[i][index]).text() + '",';
}
row.slice(0, row.length - 1);
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//Generate a file name
var fileName = "Manage_";
fileName += ReportTitle.replace(/ /g, "_");
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
</script>
答案 0 :(得分:1)
我的建议是,不要重新发明轮子。 CSV有很多问题。只需使用已经存在的库,papaparse。
这里是获取JSON对象并将其转换为CSV的函数: http://papaparse.com/docs#json-to-csv
如果您想跳过第一行,只需将arrData.slice(1)
传递给它而不是arrData
如果你想添加自己的标题,那就是第三个函数签名的用途......就像这样:Papa.unparse({fields:['a','b','c'],data:arrData})
答案 1 :(得分:0)
您是否尝试过将第一个循环中的i初始化为1? 此外,您的jQuery选择器应该是$('div')
for (var i = 1; i < arrData.length; i++) {
var row = "";
for (var index in arrData[i]) {
row += '"' + $('<div>').html(arrData[i][index]).text() + '",';
}
row.slice(0, row.length - 1);
CSV += row + '\r\n';
}