我使用以下代码使用Spreadsheet
gem读取excel文件。
require 'spreadsheet'
Spreadsheet.client_encoding = 'UTF-8'
book = Spreadsheet.open('C:\Users\Lev Berlin\Documents\Personal\Projects\FactsRus\Nutritional Analysis Models\Data for Rails model import.xls')
sheet1 = book.worksheet('Sheet1')
但文件未正确读取。
当我在另一个文件中取消注释require 'parseexel'
行时,文件会被正确处理。
请帮帮我;这有什么不对?
提前致谢。
答案 0 :(得分:0)
一旦你加载了工作表(这就是你用“sheet1 = ...”所做的),你需要读取该工作表中的行。你这样做:
sheet1.each do |row|
# do something interesting with a row
end
查看http://spreadsheet.rubyforge.org/files/GUIDE_txt.html了解详情。
答案 1 :(得分:0)
尝试使用以下内容..
require 'spreadsheet'
@workbook = Spreadsheet.open(MyFile.first.attachment.to_file)
@worksheet = @workbook.worksheet(0)
0.upto @worksheet.last_row_index do |index|
row = @worksheet.row(index)
@contact = Contact.new
#row[0] is the first cell in the current row, row[1] is the second cell, etc...
@contact.first_name = row[0]
@contact.last_name = row[1]
@contact.save
end