I want to create data by importing excel.

I have got the record of states in excel file and my state model has got only one field state_name.

I want to make a rake task to create all the record of all the states present in the excel file but I don't know how to work with excel.

I have created a basic rake task like this in the lib/tasks:-

namespace :state do
  task :create => :environment do
  end
end

How do I put the code which will read the excel file and create the states based on that ?

有帮助吗?

解决方案

You can put the xls file into /tmp directory. Then put gem spreadsheet into your Gemfile. Then create xls.rb class into lib with a read method.

class Xls
  require 'spreadsheet'

  def self.read file_path
    Spreadsheet.open(file_path) do |book|
      book.worksheets.each do |ws|
        0.upto ws.last_row_index do |index|
          row = ws.row(index)
          yield ws, row
        end
      end
    end
  end

end

Then, into your task..

namespace :project do
  desc "Load xls"
  task :load => :environment do
    Xls.read("xls_file_path") do |sheet, row|
      state = row[0] #row[0] = the first column of the this row. 
      YourModel.save(state: state)
    end
  end
end

其他提示

If you do it yourself you have to manage translations yourself, write all the helpers yourself and manage all the data yourself. With a library to do that you save yourself a lot of work and if you need to add or remove regions you can do that quickly and easily. I don't recommend doing it yourself.

If you are intent on doing it yourself then your best bet is to save the data in CSV format in a predictable way and read through the CSV creating entries. Assuming your CSV to be something of the format:

State,Country
Alabama,USA
Arkansas,USA
...

It would be simple to parse it:

require "csv"

task :load_states => :environment do
  CSV.foreach(csv_file, {headers: :first_row}) do |row|
    state = State.create(name: row["State"])
    state.country = Country.where(name: row["Country"]).first_or_create
    state.save
  end
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top