Javascript / jQuery:以CSV格式导出数据无法在IE中运行

时间:2013-08-12 11:20:09

标签: javascript export-to-csv

我需要将表格中显示的数据导出为CSV格式。我已经尝试了很多东西,但无法让它适用于IE 9及更高版本。

我的代码created a dummy fiddle

var data = [
    ["name1", "city1", "some other info"],
    ["name2", "city2", "more info"]
];//Some dummy data

var csv = ConvertToCSV(data);//Convert it to CSV format
var fileName = "test";//Name the file- which will be dynamic

if (navigator.userAgent.search("MSIE") >= 0) {
    //This peice of code is not working in IE, we will working on this
    //TODO
    var uriContent = "data:application/octet-stream;filename=" + fileName + '.csv' + "," + escape(csv);
    window.open(uriContent + fileName + '.csv');
} else {
    var uri = 'data:text/csv;charset=utf-8,' + escape(csv);
    var downloadLink = document.createElement("a");
    downloadLink.href = uri;
    downloadLink.download = fileName + ".csv";
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}

我在Stackoverflow中看到了许多链接,但找不到任何与IE9或更高版本一起使用的链接。像@ Terry Young explains in how-to-data-export-to-csv-using-jquery-or-javascript

一样

另外,尝试过 -

var csv = ConvertToCSV(_tempObj);
        var fileName = csvExportFileName();
        if (navigator.appName != 'Microsoft Internet Explorer') {
            window.open('data:text/csv;charset=utf-8,' + escape(str));
        }
        else {
            var popup = window.open('', 'csv', '');
            popup.document.body.innerHTML = '<pre>' + str + '</pre>';
        }

不确定如何修复它。我不想点击服务器并导出我的CSV(要求这样说)。

6 个答案:

答案 0 :(得分:16)

使用Javascript后,它将解决您的问题。

将此用于IE,

var IEwindow = window.open();
IEwindow.document.write('sep=,\r\n' + CSV);
IEwindow.document.close();
IEwindow.document.execCommand('SaveAs', true, fileName + ".csv");
IEwindow.close();

有关详细信息,我已经编写了相关的教程,请参阅 - Download JSON data in CSV format Cross Browser Support

希望这会对你有所帮助。

答案 1 :(得分:6)

对于IE 10+,你可以这样做:

var a = document.createElement('a');
        if(window.navigator.msSaveOrOpenBlob){
            var fileData = str;
            blobObject = new Blob([str]);
            a.onclick=function(){
                window.navigator.msSaveOrOpenBlob(blobObject, 'MyFile.csv');
            }
        }
        a.appendChild(document.createTextNode('Click to Download'));
        document.body.appendChild(a);

我认为在早期版本的IE中不可能。不调用activeX对象,但如果可以接受,则可以使用:

var sfo=new ActiveXObject('scripting.FileSystemObject');
var fLoc=sfo.CreateTextFile('MyFile.csv');
fLoc.WriteLine(str);
fLoc.close();

将文件直接写入用户的文件系统。但是,这通常会提示用户询问是否要允许脚本运行。可以在Intranet环境中禁用该提示。

答案 2 :(得分:4)

我得到了支持IE 8+的解决方案。我们需要指定分隔符,如下所示。

if (navigator.appName == "Microsoft Internet Explorer") {    
    var oWin = window.open();
    oWin.document.write('sep=,\r\n' + CSV);
    oWin.document.close();
    oWin.document.execCommand('SaveAs', true, fileName + ".csv");
    oWin.close();
  }  

您可以浏览http://andrew-b.com/view/article/44

链接

答案 3 :(得分:4)

这也是我在IE 10+版本中使用和工作的答案之一:

var csv = JSON2CSV(json_obj);            
var blob = new Blob([csv],{type: "text/csv;charset=utf-8;"});

if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, "fileName.csv")
    } else {
        var link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", "fileName.csv");
            link.style = "visibility:hidden";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }           
    }

希望这有帮助。

答案 4 :(得分:1)

这适用于任何浏览器,无需jQuery。

  1. 在页面的任何位置添加以下iframe:

    <iframe id="CsvExpFrame" style="display: none"></iframe>

  2. 为您要导出的页面中的表格提供ID:

    <table id="dataTable">

  3. 自定义链接或按钮以调用ExportToCsv函数,将默认文件名和表的id作为参数传递。例如:

    <input type="button" onclick="ExportToCsv('DefaultFileName','dataTable')"/>

  4. 将此内容添加到您的JavaScript文件或部分:

  5. &#13;
    &#13;
    function ExportToCsv(fileName, tableName) {
      var data = GetCellValues(tableName);
      var csv = ConvertToCsv(data);
      if (navigator.userAgent.search("Trident") >= 0) {
        window.CsvExpFrame.document.open("text/html", "replace");
        window.CsvExpFrame.document.write(csv);
        window.CsvExpFrame.document.close();
        window.CsvExpFrame.focus();
        window.CsvExpFrame.document.execCommand('SaveAs', true, fileName + ".csv");
      } else {
        var uri = "data:text/csv;charset=utf-8," + escape(csv);
        var downloadLink = document.createElement("a");
        downloadLink.href = uri;
        downloadLink.download = fileName + ".csv";
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
      }
    };
    
    function GetCellValues(tableName) {
      var table = document.getElementById(tableName);
      var tableArray = [];
      for (var r = 0, n = table.rows.length; r < n; r++) {
        tableArray[r] = [];
        for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
          var text = table.rows[r].cells[c].textContent || table.rows[r].cells[c].innerText;
          tableArray[r][c] = text.trim();
        }
      }
      return tableArray;
    }
    
    function ConvertToCsv(objArray) {
      var array = typeof objArray != "object" ? JSON.parse(objArray) : objArray;
      var str = "sep=,\r\n";
      var line = "";
      var index;
      var value;
      for (var i = 0; i < array.length; i++) {
        line = "";
        var array1 = array[i];
        for (index in array1) {
          if (array1.hasOwnProperty(index)) {
            value = array1[index] + "";
            line += "\"" + value.replace(/"/g, "\"\"") + "\",";
          }
        }
        line = line.slice(0, -1);
        str += line + "\r\n";
      }
      return str;
    };
    &#13;
    <table id="dataTable">
      <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Email</th>
      </tr>
      <tr>
        <td>Andrew</td>
        <td>20</td>
        <td>andrew@me.com</td>
      </tr>
      <tr>
        <td>Bob</td>
        <td>32</td>
        <td>bob@me.com</td>
      </tr>
      <tr>
        <td>Sarah</td>
        <td>19</td>
        <td>sarah@me.com</td>
      </tr>
      <tr>
        <td>Anne</td>
        <td>25</td>
        <td>anne@me.com</td>
      </tr>
    </table>
    
    <a href="#" onclick="ExportToCsv('DefaultFileName', 'dataTable');return true;">Click this to download a .csv</a>
    &#13;
    &#13;
    &#13;

答案 5 :(得分:0)

使用Blob对象 创建一个blob对象并使用msSaveBlob或msSaveOrOpenBlob 该代码在IE11中工作(未针对其他浏览器进行测试)

    <script>


 var csvString ='csv,object,file';
    var blobObject = new Blob(csvString); 

        window.navigator.msSaveBlob(blobObject, 'msSaveBlob_testFile.txt'); // The user only has the option of clicking the Save button.
        alert('note the single "Save" button below.');

        var fileData = ["Data to be written in file."];
    //csv string object inside "[]"
        blobObject = new Blob(fileData);
        window.navigator.msSaveOrOpenBlob(blobObject, 'msSaveBlobOrOpenBlob_testFile.txt'); // Now the user will have the option of clicking the Save button and the Open button.`enter code here`
        alert('File save request made using msSaveOrOpenBlob() - note the two "Open" and "Save" buttons below.');
      </script>