簡體   English   中英

Javascript / jQuery:以CSV格式導出數據無法在IE中運行

[英]Javascript/ jQuery : Exporting data in CSV not working in IE

我需要將表格中顯示的數據導出為CSV格式。 我已經嘗試了很多東西,但無法讓它適用於IE 9及更高版本。

我用我的代碼創建了一個虛擬小提琴

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在如何使用數據導出到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(要求這樣說)。

使用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();

有關更多信息,我已經編寫了相關的教程,請參閱 - 以CSV格式下載跨瀏覽器支持的JSON數據

希望這對你有所幫助。

對於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環境中禁用該提示。

這也是我使用的解決方案之一,並且適用於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);
        }           
    }

希望這可以幫助。

我得到了支持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鏈接

這將適用於任何瀏覽器,無需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文件或部分:

 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; }; 
 <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> 

使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM