Monday 21 January 2013

Importing an excelsheet -ruby on rails

I recently used roo gem for importing an excel sheet into your ruby on rails application.
Below are the steps for it :

Step 1: Add the line gem 'roo' in your gem file
Step 2: Run bundle install
Step 3:Add a method in your controller :-
Suppose your controller name is Decoration
          
def import
  Decoration.import(params[:file])
  redirect_to root_url, notice: "decorations imported."
end

Step 4: In your model add the import method as follows:
Here your model name is Decoration

def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    decoration = find_by_id(row["id"]) || new
    decoration.attributes = row.to_hash.slice(*accessible_attributes)
    decoration.save!
  end
end

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Csv.new(file.path, nil, :ignore)
  when ".xls" then Excel.new(file.path, nil, :ignore)
  when ".xlsx" then Excelx.new(file.path, nil, :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end

Step 5 :In the config/application.rb file add this line:

require 'iconv'
 

Step 6: Add this this line to your routes.rb file

resources :decorations do
  collection { post :import }
end

Step7: Add the interface for importing the excel file using below lines:

<%= form_tag import_decorations_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import" %>
<% end %>


Note: Only. xls file can be imported using the above method.

No comments:

Post a Comment