2014-01-17 57 views
9

我與一些JavaScript搞亂下載一些CSV文本:使用Javascript - 下載CSV爲文件

<script> 
var data = '"Column One","Column Two","Column Three"'; 
window.location.href = 'data:text/csv;charset=UTF-8,' + encodeURIComponent(data); 
</script> 

到目前爲止,這是工作,但隨着瀏覽器提示我要保存文件,沒有文件名也不擴展。

我該如何預先確定文件的名稱以及它的擴展名,在window.location.href之內?

+0

根據目標客戶機上,可以考慮HTML5 ['的download'屬性''(https://developer.mozilla.org/en-US/docs /網絡/ HTML /元/年#ATTR下載)。 – Passerby

+0

[將JavaScript數據導出到CSV文件而無需服務器交互]可能的副本(http://stackoverflow.com/questions/17836273/export-javascript-data-to-csv-file-without-server-interaction) – adeneo

回答

13
function downloadFile(fileName, urlData) { 

    var aLink = document.createElement('a'); 
    var evt = document.createEvent("HTMLEvents"); 
    evt.initEvent("click"); 
    aLink.download = fileName; 
    aLink.href = urlData; 
    aLink.dispatchEvent(evt); 
} 

var data = '"Column One","Column Two","Column Three"'; 
downloadFile('2.csv', 'data:text/csv;charset=UTF-8,' + encodeURIComponent(data)); 

http://jsfiddle.net/rooseve/7bUG8/

+1

不要忘記「去除」元素。 –

6

在我而言,事實證明,Excel中忽略的charset = UTF-8部分。我發現一個solution in this post,強制Excel考慮到UTF-8。因此,這最後一行並獲得成功對我來說:

downloadFile('2.csv', 'data:text/csv;charset=UTF-8,' + '\uFEFF' + encodeURIComponent(data)); 
+0

非常感謝,這可能與問題無關,但它幫助我解決了難題。 –

3

更新Andrew's Answer避免使用過時的功能。

來源:https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#The_old-fashioned_way

//Triggers a download of the given file 
//@see https://stackoverflow.com/questions/21177078/javascript-download-csv-as-file 
//@see https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#The_old-fashioned_way 
// 
//@param fileName {string} - Name of the file to download include file extension 
//@param urlData {string} - Encoded URI of the document data 
function downloadFile(fileName, urlData) { 

    var aLink = document.createElement('a'); 
    aLink.download = fileName; 
    aLink.href = urlData; 

    var event = new MouseEvent('click'); 
    aLink.dispatchEvent(event); 
} 

var data = '"Column One","Column Two","Column Three"'; 
downloadFile('2.csv', 'data:text/csv;charset=UTF-8,' + encodeURIComponent(data)); 
+0

文件正在使用fileUrl(urlData)而不是fileName保存。 –