Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a CSV file in Ruby on Rails?

Tags:

In my InvoicesController I have this:

def index
  @invoices = current_user.invoices
  respond_to do |format|
    format.html
    format.xls
    format.csv # not working!
  end
end

In my index.html.erb view I have these two download links:

<%= link_to "Download as Excel", invoices_path(:format => "xsl") %>
<%= link_to "Download as CSV", invoices_path(:format => "csv") %>

The templates index.xsl.erb and index.csv.erb do exist as well.

The first link works, i.e. the Excel file gets downloaded to the user's computer. However, the CSV file is rendered in the browser and not downloaded.

What must I do to enable users to download CSV files as well?

Thanks for any help.

like image 289
Tintin81 Avatar asked Jun 09 '13 22:06

Tintin81


People also ask

How do I save a csv file in rails?

First, set up the application and seed in some data. Now, in post. rb , declare a method which will be responsible for generating data in CSV format. Depending upon your Rails version and the dependencies added, it's possible you'll need to add a require statement.


2 Answers

Try specifying the appropriate content headers and explicitly rendering your index.csv.erb template in your format.csv handler block.

# app/controllers/invoices_controller.rb
format.csv do
    response.headers['Content-Type'] = 'text/csv'
    response.headers['Content-Disposition'] = 'attachment; filename=invoice.csv'    
    render :template => "path/to/index.csv.erb"
end
like image 65
zeantsoi Avatar answered Sep 19 '22 13:09

zeantsoi


Try this

format.csv do
  response.headers["Content-Type"] = "text/csv; charset=UTF-8; header=present"
  response.headers["Content-Disposition"] = "attachment; filename=invoices.csv"
end
like image 35
usha Avatar answered Sep 22 '22 13:09

usha