Last active
December 18, 2015 00:58
-
-
Save manusajith/5699910 to your computer and use it in GitHub Desktop.
Import data from excel file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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