2012-09-04 43 views
1

我正在使用以下代碼來讀取使用Spreadsheet gem的excel文件。Ruby on Rails - 使用電子表格讀取xls文件RubyGem

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

你說的「不讀正確」意味着你得到一個錯誤信息;?是你在程序中獲取數據不匹配什麼是在該文件;有沒有數據轉換問題...? – JESii

+0

不,我沒有收到任何錯誤。但它返回電子表格對象而不是返回行值。 – Dipali

回答

0

一旦您已加載的工作表(也就是你用「工作表Sheet1 = ...做了什麼),你需要從表讀取行你這樣做,像這樣:

sheet1.each do |row| 
    # do something interesting with a row 
    end 

退房http://spreadsheet.rubyforge.org/files/GUIDE_txt.html欲瞭解更多信息

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 
+0

請不要使用如此多的標題 – bronislav