Export data to CSV and Excel in your Rails

Cloud Computing | #CloudFoundry | Ruby | Go | OpenStack | Ansible | Docker | Jenkins

A common requirement from customers is the ability to export tabular data to a CSV file that can be imported into Excel. Ruby on Rails uses the standard ruby CSV library to import test fixtures that are in CSV format.

Below are the steps we need to follow.

1. require the CSV library to controller, Where we need to write import code

require 'csv'

2. Emport code in controller

def export_to_csv       
    @users = User.find(:all)
    csv_string = CSV.generate do |csv|
         csv << ["Id", "Name", "Email","Role"]
         @users.each do |user|
           csv << [user.id, user.name, user.name, user.role]
         end
    end         
  
   send_data csv_string,
   :type => 'text/csv; charset=iso-8859-1; header=present',
   :disposition => "attachment; filename=users.csv" 
end @users = User.find(:all)
Fetching all user details and assigned on @users
csv_string = CSV.generate do |csv|
Using CSV class generate method to create csv file
csv << ["Id", "Name"…

View original post 40 more words

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