CSV file format is very popular when we want to give option to export or import tabular data in our application. Rails has a very good support to do this. In this post I will discuss both exporting and importing to CSV file in Rails application.
For our export and import purpose, we will use a table named USERS which is like below:

Import From CSV:
Import information from any comma separated CSV file is so simple in Rails. Here, we want to import user information to insert users in our USERS table and the information into CSV file is like below:

To import this we need a view from where we can submit our CSV file through a multipart form. Here is a simple form view:
<% form_tag url_for(:controller => "export_import", :action => "import_user_from_csv"), {:multipart => true} do -%>
<%= file_field_tag :csv_file -%>
<%= submit_tag 'Import' -%>
<% end -%>
After submitting this form it will goes to the specified action(in our case it will goes to controller: “ExportImportController” and action: “import_user_from_csv” ) from where we will actually import the necessary information from the file uploaded. The code of the action is like below:
require "csv"
class ExportImportController < style="font-style: italic;">
def index
end
def import_user_from_csv
# parse the csv file using ruby "csv"-librarty
parsed_file = CSV::Reader.parse(params[:csv_file])
# print all rows of the csv file into the log file
parsed_file.each do |row|
logger.info "Information From CSV >> Id : #{row[0].inspect} Name: #{row[1].inspect} Email: #{row[2].inspect}"
end
redirect_to :action => :index
end
end
Here one important thing is that, we are using require "csv" which library provides us option to parse csv file.
I am not showing how to insert this information into Database. Because, once we have all information on our hand, we can play with it in any way we want. I am just giving an idea. Place the following code into the loop(parsed_file.each do |row|):
if(User.exists?(row[0]))
User.update(row[0], {:name => row[1], :email => row[2]})
else
User.create(:name => row[1], :email => row[2])
end
Above line will insert information into USERS table. But, we can not use it directly in our application as we need to handle all kind of exceptions.
Export to CSV:
There is a FasterCSV ruby library which provides easy way to export our information to CSV file. To use it you can install gems using “gem install fastercsv” or download it from http://fastercsv.rubyforge.org/ and extract it to RAILS_HOME/vendor/plugins/fastercsv.
Suppose we want to export all users of USERS table to CSV file. FasterCSV provides a output stream in which we can insert arrays as rows(one array one row) to CSV file using “<<”. Once we have the streaming data we can send it to the browser.
Following code can be used to export all users to "users.csv":
class ExportImportController < ApplicationController
def export_users
# get all users from user table
users = User.find(:all)
# generate the streaming data
csv_string = FasterCSV.generate do |csv|
csv << ["Id", "Name", "Email Address"]
users.each do |user|
csv << [user.id, user.name, user.email] end
end
# send csv file(users.csv) to browser
send_data(csv_string, :type => 'text/csv; charset=utf-8; header=present', :filename => "users.csv")
end
end