Exporting to CSV and Excel

Step 1:Open  config/application. and add the line as given below:


require 'csv'

Step 2: In controller where you want to generate the xls, add the below code.

 @events = Event.all(:name)
 respond_to do |format|  format.csv { send_data @events.to_csv }
format.xls {send_data @events.to csv(col sep: "\t")}

Step 3:Now in model of the event, add the below code.

  def csv(options = {})
    CSV.generate(options) do |csv|
      csv << column_names
      all.each do |event|
       csv << event.attributes.values_at(*column_names)

Step 4: Now open the below file and add the line to mime_types.

Mime::Type.register "application/xls", :xls

Step 5:  Now template is created as below .

<table border="1">
  <% @events.each do |event| %>
    <td><%= event.id %></td>
    <td><%= event.name %></td>
    <td><%= event.date %></td>
    <td><%= event.venue %></td>
  <% end %>

Step 6 :Now add the links to the page where the xls is generated, here i have pasted on the top of the page so in my out put the links are shown on the top of the page.


<h1>Events List</h1>

  <%= link_to "CSV", products_path(format: "csv") %> |
  <%= link_to "Excel", products_path(format: "xls") %>

Step 7: Now you will see the download links on the top of the page as shown below.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s