gpt4 book ai didi

ruby-on-rails - Rails : Excel columns, 种子

转载 作者:行者123 更新时间:2023-12-04 20:18:27 24 4
gpt4 key购买 nike

我创建了一个带有列 ID、任务、描述的 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数据?

最佳答案

我用 roo将excel导入我的rails应用程序。做到这一点并不难。您可以观看the railscasts如果你愿意,可以从 Ryan Bates 那里得到 roo。

我给你我的 roo 示例代码

gem 文件

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

Controller :
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 上(看上面的 Controller )

希望能帮到你..!

关于ruby-on-rails - Rails : Excel columns, 种子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14993978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com