Rails - CSV 导出:提示文件下载
我想让我的用户能够将表导出为 CSV。
因此,在我的控制器中,我在文件顶部添加了:
respond_to :html, :js, :csv
如果请求的格式是 csv,我还会设置标头:
if params[:format] == 'csv'
generate_csv_headers("negotiations-#{Time.now.strftime("%Y%m%d")}")
end
generate_csv_headers
(在 application_controller 中)的代码是:
def generate_csv_headers(filename)
headers.merge!({
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Type' => 'text/csv',
'Content-Disposition' => "attachment; filename=\"#{filename}\"",
'Content-Transfer-Encoding' => 'binary'
})
end
我还创建了一个名为 index.csv.erb
的视图来生成我的文件:
<%- headers = ["Id", "Name"] -%>
<%= CSV.generate_line headers %>
<%- @negotiations.each do |n| -%>
<%- row = [ n.id,
n.name ] -%>
<%= CSV.generate_line row %>
<%- end -%>
我没有任何错误,但它只是显示 CSV 文件的内容,而我希望浏览器会提示下载文件。
我读了很多书,但找不到任何有用的东西。 你有主意吗?
谢谢,p。
I want to give my users the ability to export a table to CSV.
So in my controller, I've added on top of the file:
respond_to :html, :js, :csv
I'm also setting the headers if the requested format is csv:
if params[:format] == 'csv'
generate_csv_headers("negotiations-#{Time.now.strftime("%Y%m%d")}")
end
Code for generate_csv_headers
(in application_controller) is:
def generate_csv_headers(filename)
headers.merge!({
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Type' => 'text/csv',
'Content-Disposition' => "attachment; filename=\"#{filename}\"",
'Content-Transfer-Encoding' => 'binary'
})
end
I've also created a view named index.csv.erb
to generate my file:
<%- headers = ["Id", "Name"] -%>
<%= CSV.generate_line headers %>
<%- @negotiations.each do |n| -%>
<%- row = [ n.id,
n.name ] -%>
<%= CSV.generate_line row %>
<%- end -%>
I don't have any error, but it simply displays the content of the CSV file, while I'd expect a prompt from the browser to download the file.
I've read a lot, but could not find anything that'd work.
Do you have an idea?
thanks, p.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我仍然不确定为什么这解决了问题,但它确实解决了。
我将视图中的链接更改为
,现在可以使用了!
I'm still unsure about why this fixed the issue, but it did.
I changed the link in the view to
and it now works!
我不确定你必须这样做,但如果你生成并保存文件,你可以使用 send_file 将其发送到浏览器。请参阅http://api.rubyonrails.org/classes/ActionController/Streaming.html
I'm not sure you have to do it this way, but if you generate and save the file, you can use send_file to send it to the browser. See http://api.rubyonrails.org/classes/ActionController/Streaming.html
您可能对我制作的名为 CSV shaper 的 gem 感兴趣,它允许您使用非常好的 Ruby DSL 创建 CSV 输出。
它还将处理正确设置响应标头,同时允许自定义文件名。
https://github.com/paulspringett/csv_shaper
You might be interested in this gem I made called CSV shaper that allows you to create CSV output using a really nice Ruby DSL.
It will also handle setting the response headers correctly, while allowing filename customisaton.
https://github.com/paulspringett/csv_shaper