Json转换为CSV以下载可在chrome浏览器中运行但无法在IE浏览器中运行?任何身体都有解决方案
这个。

杰森数据:

[
  {
    "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);
};

最佳答案

我在尝试解决同一问题时找到了这篇文章。

我的解决方案是使用“ 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>

09-18 00:05