Rails - CSV export: prompt for file download
Posted
by
Pierre
on Stack Overflow
See other posts from Stack Overflow
or by Pierre
Published on 2011-01-03T21:49:07Z
Indexed on
2011/01/03
21:54 UTC
Read the original article
Hit count: 298
ruby-on-rails
|csv
Hello,
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.
© Stack Overflow or respective owner