How to import CSV file in rails

How to import CSV file in rails?

The CSV text-file format is a common choice for both import and export when performing data migrations. What if you want to import CSV files within a Rails application?

Here is the code that allow you to upload CSV data onto the MySQL database from the web interface
This code save data direct to database without saving it to temp file

Controller:


require ‘csv’

def csv_import
@parsed_file=CSV::Reader.parse(params[:dump][:file])
n=0
@parsed_file.each do |row|
c=CustomerInformation.new
c.job_title=row[1]
c.first_name=row[2]
c.last_name=row[3]
if c.save
n=n+1
GC.start if n%50==0
end
flash.now[:message]=”CSV Import Successful, #{n} new records added to data base"
end

View:

your view will look like


<% form_for :dump, :url=>{:controller=>”customer_informations”,
:action=>"csv_import"},
:html => { :multipart => true } do |f| -%>
< label for="dump_file" >
Select a CSV File :
</label >
<%= f.file_field :file -%>
<%= submit_tag 'Submit' -%>
<% end -%>

Author-icon Published by : Satish Chauhan @ 29 Jun, 2007 at 01:18PM
How to generate CSV files in Rails

The CSV text-file format is a common choice for both import and export when performing data migrations. What if you want to generate CSV files from the database records and want to export within a Rails application?

Here is the code that allow you to generate CSV file form the database records


Controller:


require 'csv'

def export_to_csv
@customers=CustomerInformation.find(:all)
report = StringIO.new
CSV::Writer.generate(report, ',') do |title|
title << ['Id','Job Title','First Name','Last Name']
@customers.each do |c|
title << [c.id,c.job_title,c.first_name,c.last_name]
end
end
report.rewind
send_data(report.read,:type=>'text/csv;charset=iso-8859-1;
header=present',:filename=>'report.csv',
:disposition =>'attachment', :encoding => 'utf8')
end

View:

Your view will look like


<% form_tag({ :action => :export_to_csv })do -%>
<%= submit_tag "Export To CSV" -%>
<% end -%>

Author-icon Published by : Satish Chauhan @ 25 Jun, 2007 at 10:08AM
Sponsored Links