Nithin Bekal

Posts About Notes Slides

Export to CSV in Rails

01 Feb 2014

Exporting data to CSV from a Rails app is as simple as adding a respond_to block to the controller action and setting the proper response headers.

As an example, let’s consider a users#index action which lists the users for admin. Now if you want to allow the admin to download the list as CSV, this is how it can be done:

Require Ruby’s built in CSV library in ApplicationController.

require 'csv'

In users#index, add a respond_to block with HTML and CSV formats. In the format.csv block, set the ‘Content-Type’ and the ‘Content-Disposition’ headers. (The latter lets you set the name of the downloaded file.)

def index
  @users = User.all
  respond_to do |format|
    format.html
    format.csv do
      headers['Content-Disposition'] = "attachment; filename=\"user-list\""
      headers['Content-Type'] ||= 'text/csv'
    end
  end
end

Create an erb file at app/views/users/index.csv.erb with the CSV data. Let’s only include name and email fields for this example.

<%- headers = ['Name', 'Email'] -%>
<%= CSV.generate_line headers %>
<%- @users.each do |user| -%>
<%= CSV.generate_line([user.name, user.email]) -%>
<%- end -%>

Now you can link to your CSV download using the normal link helpers with the format option like this:

<%= link_to 'Download CSV list', users_path(format: :csv) %>

And that’s it. It just works.

Hi, I’m Nithin Bekal, a software craftsman with over 7 years of experience in shipping web applications. I mostly use Ruby, but lately have also been exploring Elixir. Co-founder of CrowdStudio.in, and helping organize Rubyconf India. Tweet to me at @nithinbekal.