2014-01-17 56 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保存。 –