Rails:Excel列,种子

时间:2013-02-21 03:17:19

标签: ruby-on-rails excel

我创建了一个包含列id,任务,描述

的Excel工作表

我找到了这个并把它放在我的种子里.rb:

require 'spreadsheet'


Spreadsheet.open('/db/data/uebung.xls') do |uebung|
  book.worksheet('Sheet1').each do |row|
  break if row[0].nil?
  puts row.join(',')
end
end

我收到此消息:

  [DEPRECATED] By requiring 'parseexcel', 'parseexcel/parseexcel' and/or
         'parseexcel/parser' you are loading a Compatibility layer which
         provides a drop-in replacement for the ParseExcel library. This
         code makes the reading of Spreadsheet documents less efficient and
         will be removed in Spreadsheet version 1.0.0

你怎么看?是不是很容易导入excel数据?

1 个答案:

答案 0 :(得分:2)

我使用roo将excel导入我的rails应用。这样做并不难。如果你愿意的话,你可以从Ryan Bates看the railscasts用roo来做。

我给你我的示例代码roo

的Gemfile

gem 'rubyzip'
gem 'spreadsheet'
gem 'nokogiri'
gem 'roo'

控制器:

def import
  @trainerone = Trainerone.find(params[:trainerone_id])

  Trainerone.import(params[:file], @trainerone.id)
  redirect_to @trainerone, notice: "Import Success."
end

型号:

def self.import(file, trainer_id)
  trainerone = Trainerone.find(trainer_id)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    trainer = Trainerone.create! row.to_hash
  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
end

视图:

<%= form_tag import_trainerones_path(@trainerone.id), multipart: true do %>
    <%= file_field_tag :file %>
    <%= submit_tag "Import" %>
<% end %>

import_trainerones_path取自route,指向您action: import上的trainerone controller(请查看上方的控制器)

希望可以帮助你......!