Skip to content

Instantly share code, notes, and snippets.

@manusajith
Last active December 18, 2015 00:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manusajith/5699910 to your computer and use it in GitHub Desktop.
Save manusajith/5699910 to your computer and use it in GitHub Desktop.
Import data from excel file
Sample data
|Name | mobile_number |
|Manu | 9447786299 |
|User | 94477xxxxx |
#Step1. install the required spreadsheet gem by entering:
$ sudo gem install spreadsheet
#step2: in the view place the form to be submitted to a specific action.
<% form_for :dump, :url=>{:controller=>"students", :action=>"excel_import"}, :html => { :multipart => true } do |f| -%>
#Select an Excel File :
<%= f.file_field :excel_file -%>
<%= submit_tag 'Submit' -%>
<% end -%>
#step3: In the controller action:
require 'spreadsheet'
def excel_import
Spreadsheet.client_encoding = 'UTF-8'
book = Spreadsheet.open params[:dump][:excel_file]
sheet1 = book.worksheet 0
sheet1.each do |row|
# you can do any interesing thing with row
Student.new(:name => row[0], :mobile => row[1]).save
end
end
#Thats it for importing spreadsheet to your database.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment