Json到CSV下载,可以在chrome中工作,但不能在IE浏览器中工作



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 withnand 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 + 'rn';
       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 + 'rn';
       }
       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编码的数据设置到窗口中,但它阻碍了我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>

相关内容

最新更新