[英]Ruby on Rails -Reading xls file using Spreadsheet RubyGem
我正在使用以下代碼使用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'
另一個文件中的require 'parseexel'
行時,文件將被正確處理。
請幫我; 這是怎么了
提前致謝。
加載工作表后(這就是對“ sheet1 = ...所做的操作”),您需要讀取該工作表中的行。您可以這樣做:
sheet1.each do |row|
# do something interesting with a row
end
請查看http://spreadsheet.rubyforge.org/files/GUIDE_txt.html了解更多信息。
嘗試如下使用。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.