2013-08-12 2 views
18

테이블에 표시된 데이터를 CSV 형식으로 내 보내야합니다. 나는 많은 것을 시도했지만 Internet Explorer 9 이상에서는 작동하지 않습니다.Javascript/jQuery : IE에서 CSV의 데이터 내보내기가 작동하지 않습니다.

내 코드가 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를 내보내고 싶지 않습니다 (요구 사항은 그렇게 말합니다).

당신이 할 수있는 10 + IE를 들어
+0

@Shubh 당신은 전혀이 문제를 해결 않았다 - 내가 직면하고있다 동일한 문제 -이 해결 방법을 살펴 보았습니다 - http://blog.paxcel.net/blog/savedownload-file-using-html5-javascript-the-download-attribute-2/하지만 나를 위해 일한 적이 없습니다 – anna

+0

@anna '아니야. '나는 그것을 풀 수 없었다. 마지막으로 원하는 것을 얻으려면 Server Side 논리를 사용해야했습니다. – Shubh

+0

감사합니다. 계속 악몽을 꾸며야 할 것입니다. – anna

답변

15

을 통해 갈 수 있습니다. 내가 그에 자습서를 작성했습니다 자세한 내용은 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 파일 자체에 실제로 삽입하지 않고 구분 기호를 지정하는 방법이 있습니까? (OP와 비슷한 방법을 사용하는) Chrome에서 CSV를 생성 할 때 Excel에서 'sep ='행없이 CSV를 열 수 있습니다. – JLewkovich

+0

최신 브라우저와 IE8을 지원해야합니다. 이 코드는 엄청난 도움이되었습니다. 감사! –

6

:

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

파일을 사용자의 파일 시스템에 직접 쓰는 것이 좋습니다. 그러나 일반적으로 사용자는 스크립트 실행을 허용할지 묻는 메시지를 표시합니다. 인트라넷 환경에서는 프롬프트를 비활성화 할 수 있습니다.

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를 전달하십시오. 테이블의 매개 변수로.예를 들어 :

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

이것은 또한 내가 사용하고 작업에 대한 답변 중 하나입니다

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

  • 는 자바 스크립트 파일 또는 섹션이 추가 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

    관련 문제