Exporting to CSV and Excel

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

/config/application.rb

require 'csv'

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

/controllers/events_controller.rb
 @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.

/models/event.rb
  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.

initializers/mime_types.rb
Mime::Type.register "application/xls", :xls

Step 5:  Now template is created as below .

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

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.

views/events/list.html.erb

<h1>Events List</h1>

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

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

fdsfdsfdsfdsfdsf

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s