Javascript-将CSV下载为文件 [英] Javascript - Download CSV as File

查看:75
本文介绍了Javascript-将CSV下载为文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在弄乱一些JavaScript,以下载一些csv文本:

I'm messing with some javascript to download some csv text:

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

到目前为止,这是可行的,但是当浏览器提示我保存文件时,没有文件名,也没有扩展名.

So far this is working, but as the browser prompts me to save the file, there is no filename, nor extension.

如何在window.location.href内预先确定文件名及其扩展名?

How can I predetermine the name of the file and it's extension, inside the window.location.href ?

推荐答案

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/

这篇关于Javascript-将CSV下载为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆