2011-01-28 54 views
13

我希望能夠上傳包含聯繫信息的Excel文件。然後,我能夠解析它併爲我的Contact模型創建記錄。如何在Rails中上傳和解析Excel文件?

我的應用程序是一個Rails應用程序。

我在heroku上使用了paperclip gem,我已經能夠將vim卡解析爲Contact模型,並且正在尋找類似的東西,但會遍歷Excel文件的所有行。

寶石,簡化任務和示例代碼解析將是有益的!

回答

17

電子表格是迄今爲止我發現的最好的Excel解析器。它提供了很多功能。

你說你使用回形針是很好的附件。但是,如果您將附件存儲在S3中(我假設您使用Heroku後),將文件傳遞到電子表格的語法稍有不同,但並不困難。

下面是一個純粹的語法的例子,可以使用和不放置在任何類或模塊,因爲我不知道你打算如何開始解析聯繫人。

# load the gem 
require 'spreadsheet' 

# In this example the model MyFile has_attached_file :attachment 
@workbook = Spreadsheet.open(MyFile.first.attachment.to_file) 

# Get the first worksheet in the Excel file 
@worksheet = @workbook.worksheet(0) 

# It can be a little tricky looping through the rows since the variable 
# @worksheet.rows often seem to be empty, but this will work: 
0.upto @worksheet.last_row_index do |index| 
    # .row(index) will return the row which is a subclass of Array 
    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 
10

我在我的一個Rails 2.1.0應用程序中有類似的需求。我解決它以下列方式:

在「LIB」文件夾中我寫了這樣的模塊:

require 'spreadsheet' 

module DataReader 
    def read_bata(path_to_file) 
    begin 
     sheet = book.worksheet 0 
     sheet.each 2 do |row| 
     unless row[0].blank? 
      # Create model and save it to DB 
      ... 
     end 
     end 
    rescue Exception => e 
     puts e 
    end 
    end 
end 

有一個模型上傳:

class Upload < AR::Base 
    has_attached_file :doc, 
    :url => "datafiles/:id", 
    :path => ":rails_root/uploads/:id/:style/:basename.:extension" 

    # validations, if any 
end 

產生UploadsController這將處理將文件上傳並保存到適當的位置。我用Paperclip進行文件上傳。

class UploadsController < AC 
    include DataReader 

    def new 
    @upload = Upload.new 
    end 

    def create 
    @upload = Upload.new(params[:upload]) 

    @upload.save 
    file_path = "uploads/#{@upload.id}/original/#{@upload.doc_file_name}" 
    @upload.read = DataReader.read_data(file_path) 

    # respond_to block 
    end 
end 

閱讀有關 '電子表格' 庫herehere。你可以做出適當的改進,並使技術在Rails 3中工作。希望這有助於。

+1

喜,看起來像你得到了一些很好的upvotes ...通過它還在讀書......你建有回形針上傳?它在上傳時讀取數據? – Angela 2011-02-01 16:53:45

+0

您是否需要創建單獨的視圖和表單來上傳文件? – Angela 2011-02-01 16:54:05

0

我做了一個寶石,很容易達到這一點。我稱之爲Parxer和...

  • 它的建立在roo gem。
  • 它允許你解析xls,xlsx和csv文件。
  • 有一個DSL可以處理:
    • 列映射。
    • 文件,行和列/單元驗證。
    • 列/單元格格式。