javascript 如何导出带有文件名的csv文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13405981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to export csv file with filename
提问by user1827864
I want to export the exist data into csv file. I try to use this code:
我想将现有数据导出到 csv 文件中。我尝试使用此代码:
var uriContent = "data:text/csv;charset=utf-8," + encodeURIComponent(data);
var myWindow = window.open(uriContent);
myWindow.focus();
it works but I can design filename. I can only get the dialog with name like "MVeAnkW8.csv.part" which I don't know where the name come from.
它有效,但我可以设计文件名。我只能得到名称为“MVeAnkW8.csv.part”之类的对话框,我不知道名称来自哪里。
How can I assign filename in the first dialog? Thanks in advance.
如何在第一个对话框中分配文件名?提前致谢。
update:
更新:
I am now using rails. Actually I have a method in server side names export_to_csv. In end of this method, I use code like that:
我现在正在使用导轨。实际上我在服务器端名称 export_to_csv 中有一个方法。在这个方法的最后,我使用了这样的代码:
send_data(csv_string,
:type => 'text/csv; charset=utf-8;',
:filename => "myfile.csv")
It works and I can specify the file name. For now, I want to use ajax to get more csv files(that is the reason why I want to use javascript, because a normal http request can only get one file to be downloaded).
它有效,我可以指定文件名。现在,我想使用ajax来获取更多的csv文件(这就是我想使用javascript的原因,因为普通的http请求只能下载一个文件)。
I use js code like that:
我使用这样的js代码:
$.post("export_to_csv",
function(data) {
var uriContent = "data:text/csv;charset=utf-8," + encodeURIComponent(data);
var myWindow = window.open(uriContent);
myWindow.focus();});
It get the data from server side and I try to transfer it into csv. I can get a file but can't specify the file name.
它从服务器端获取数据,我尝试将其传输到 csv 中。我可以获取文件但不能指定文件名。
回答by Tamás Pap
As I know, you can specify the filename only in chrome 14+. Take a look at this question: Is there any way to specify a suggested filename when using data: URI?
据我所知,您只能在 chrome 14+ 中指定文件名。看看这个问题:有没有办法在使用 data: URI 时指定建议的文件名?
Update!
更新!
If you want to download multiple csv files "at once", you can zip them together, or save each file on the server separately (each file now has a url that points to it - if you place them inside the 'www' folder). Then send the file names and their path/url to the client via ajax (use a json encoded list for example). In the ajax callback function: take the list of the files and open each file-url in a separate popup.
如果您想“一次”下载多个 csv 文件,您可以将它们压缩在一起,或者将每个文件分别保存在服务器上(每个文件现在都有一个指向它的 url - 如果您将它们放在“www”文件夹中) . 然后通过ajax将文件名及其路径/url发送到客户端(例如使用json编码列表)。在 ajax 回调函数中:获取文件列表并在单独的弹出窗口中打开每个文件 url。