Json转CSV用于下载Chrome工作但不能在IE浏览器中工作?任何机构都有解决方案 这个。
Json数据:
[
{
"id":1, "name":"Johnson, Smith, and Jones Co.",
"amount":345.33, "Remark":"Pays on time"
},
{
"id":2, "name":"Sam \"Mad Dog\" Smith",
"amount":993.44, "Remark":""
},
{
"id":3, "name":"Barney & Company",
"amount":0, "Remark":"Great to work with\nand always pays with cash."
},
{
"id":4, "name":"Johnson's Automotive",
"amount":2344, "Remark":""
}
]
功能:
JSONToCSVConvertor = function (JSONData, Filename, ColumnDataTypes, ShowLabel)
{
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var array = ColumnDataTypes.split(',');
var CSV = '';
var ColumnName = ColumnDataTypes.split(',');
if (ShowLabel) {
var row = "";
for (var x = 0; x < array.length ; x++) {
row += array[x].split('-')[1] + ',';
}
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
for (var i = 0; i < arrData.length; i++) {
var row = "";
for (Col = 0; Col < array.length; Col++) {
row += ('"' + arrData[i][array[Col].split('-')[0]] + '",').replace('""', '"');
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//Generate a file name
var fileName = Filename;
//Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
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);
};
答案 0 :(得分:0)
我在尝试解决同样的问题时发现了这篇文章。
我的解决方案是使用“Papa Parse”库创建CSV文件,并使用URL.createObjectURL()实际将本地数据显示为可下载的文件。
我还尝试将base64编码数据直接设置到窗口like this solution,但它在我的6-10MB报告结果中被阻塞。
jQuery(document).ready(function() {
//My json formatted data from php.
var dataSet = <?=json_encode($data)?>;
//select our link, create an objectURL Blob of CSV data.
jQuery('#downloadCsv').attr('href',URL.createObjectURL(new Blob([Papa.unparse(dataSet)], { type:"text/csv" } ) ) );
});
和链接的html:
<a id="downloadCsv" class="button button-secondary" download="reportdata.csv">Download CSV</a>