2013-08-12 18 views
18

我需要將表中顯示的數據導出爲CSV格式。我已經嘗試了很多東西,但無法在IE 9及更高版本上運行。Javascript/jQuery:在CSV中導出數據不在IE中工作

我有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); 
} 

我見過很多在#1的聯繫,也沒有找到任何的工作與IE9以上。像@ Terry Young explains in how-to-data-export-to-csv-using-jquery-or-javascript

此外,tried-

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(要求如此)。

+0

@Shubh你解決這個在所有 - 我對着同樣的問題 - 我看看這個解決方法 - http://blog.paxcel.net/blog/savedownload-file-using-html5-javascript-the-download-attribute-2/但它沒有爲我工作 – anna

+0

@anna 「沒有。」我無法解決它。最後,我不得不使用服務器端邏輯來獲得所需的。 – Shubh

+0

好的,謝謝你將不得不繼續尋找什麼是噩夢! – anna

回答

15

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

希望這將是對你有幫助。

+0

謝謝,這節省了我的時間。 –

+0

是否有指定一個分隔符而沒有實際插入CSV文件本身?出於某種原因,當我在Chrome中生成CSV(使用與OP中的方法類似的方法)時,Excel可以在沒有'sep =,'行 – JLewkovich

+0

的情況下打開CSV,我必須支持現代瀏覽器和IE8。這一點代碼對我非常有幫助。謝謝! –

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環境中禁用。

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

+0

鏈接已死 – ameliapond

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文件或部分:

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>[email protected]</td> 
 
    </tr> 
 
    <tr> 
 
    <td>Bob</td> 
 
    <td>32</td> 
 
    <td>[email protected]</td> 
 
    </tr> 
 
    <tr> 
 
    <td>Sarah</td> 
 
    <td>19</td> 
 
    <td>[email protected]</td> 
 
    </tr> 
 
    <tr> 
 
    <td>Anne</td> 
 
    <td>25</td> 
 
    <td>[email protected]</td> 
 
    </tr> 
 
</table> 
 

 
<a href="#" onclick="ExportToCsv('DefaultFileName', 'dataTable');return true;">Click this to download a .csv</a>

+1

這適用於Chrome,但在IE中失敗。 –

+1

這不適用於IE11。 – Madhura

3

這也是我用它和工作的一個答案適用於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); 
     }   
    } 

希望這會有所幫助。

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> 
+0

非常感謝。這個解決方案在IE11上爲我工作。 – Madhura