2013-02-21 59 views
2

我創建一個Excel工作表的列ID,任務描述的Rails:Excel列,種子

我覺得這並把它放在我的seeds.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數據不容易嗎?

回答

2

我用roo將excel導入到我的rails應用程序中。這並不難。如果你願意,你可以看Ryan Bates的the railscasts做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它在你的action: importtrainerone controller指向是從您的route採取

希望可以幫到你..!

+0

好吧,我執行此操作。我的控制器名稱是Trainerone。我不明白這在你的形式:form_tag import_sales_journal_header_sales_journal_details_path(@ sales_journal_header.id)。什麼是SalesJournalHeader? – ubuseral 2013-02-21 20:19:53

+1

我只是編輯我的答案,希望能更清楚地說明情況。 'SalesJournalHeader'是我的模型,所以你的模型應該是'Trainerone'。 'import_sales_journal_header_sales_journal_details_path'來自我的路線,你應該是'import_trainerones_path' – ksugiarto 2013-02-22 04:00:50