Thursday, December 4, 2008

Import data from CSV or Excel in to database

Simple Way To Import CSV/Excel data.

If u have excel file then save it as CSV file.
Consider a table foo and it has two columns (name,status)
Put ur CSV file in config folder
Create a migration file.. Put the below code in ur self.up method

def self.up
filename = "#{RAILS_ROOT}/config/Datafile.csv"
file=File.new(filename,"r")
while (line = file.gets)
c = Foo.new
columns = line.split(",")
c.name=columns[1]
c.status=columns[2]
c.save
end

Run the migration using rake command 'rake db:migrate --trace'
and thats it..!! You Got Ur Table Loaded With Data u Need..!!

Cheers..!!

1 comment:

களப்பிரர் - jp said...

சார், கொஞ்சம் எங்களுக்கும் புரியும்படி ஏதாவது எழுதுங்கோ !!!!