我想我可能错过了一些非常简单的东西,因为我是这个gem(以及Ruby/Rails)的新手,但现在我们开始。。。
我刚从RubyGems安装了Spreadsheet-gem,并使用Bundler进行安装。之后,我重新启动了本地服务器。
我想用Excel文件创建数据库,但很难打开文件。我的代码是:
require 'spreadsheet'
Spreadsheet.client_encoding = 'UTF-8'
book = Spreadsheet.open('C:UsersLev BerlinDocumentsPersonalProjects
FactsRusNutritional Analysis ModelsData for Rails model import.xls')
sheet1 = book.worksheet('Sheet1')
运行>rails runner script/load_excel_file.rb(上面有代码)后,我得到的错误是:
权限被拒绝-C:\Users。。。import.xls(错误号::EACCES)
就像我说的——我可能错过了一些非常简单的东西,但任何建议都将不胜感激。
问题是我试图读取的文件已打开!N00b错误,但我最终还是想通了。
谢谢大家的光临。
在gem文件中使用parseexcel而不是电子表格。
gem 'parseexcel'
在db/seed.rb文件中写下以下代码,将您的excel文件放在project/db/data文件夹中
def seed_cities
workbook = Spreadsheet::ParseExcel.parse("#{Dir.getwd}/db/data/cities.xls")
workbook.worksheet(0).each(1) { |row|
next if row == nil;
col = row.at(0);
next if col == nil;
id = col.to_s('latin1').strip;
next if id == "";
country_id = row.at(1).to_s('latin1').strip;
state_id = row.at(2).to_s('latin1').strip;
name = row.at(3).to_s('latin1').strip;
code = row.at(4).to_s('latin1').strip;
city = City.new(:country_id => country_id, :state_id => state_id, :name => name, :code => code)
unless city.save
city.errors.each { |e| puts "Database Error: ", e }
end
}
end
seed_cities()
这是我的cities.xls excel文件
id country_id state_id name code
1 7 77 Lahore LHR
2 7 77 Islamabad ISB