如何在Rails中上传和parsingExcel文件?

我希望能够上传包含联系信息的Excel文件。 然后,我可以parsing它并为我的Contact模型创buildlogging。

我的应用程序是一个Rails应用程序。

我在heroku上使用了paperclip gem,我已经能够将vim卡parsing为Contact模型,并且正在寻找类似的东西,但会遍历Excel文件的所有行。

简化任务和示例代码parsing的gem将是有益的!

电子表格是迄今为止我发现的最好的Excelparsing器。 它提供了相当多的function。

你说你使用Paperclip的附件是好的。 但是,如果您将附件存储在S3(我假设您使用Heroku后),则将文件传递到电子表格的语法有点不同,但并不困难。

下面是一个纯粹的语法的例子,可以使用,而不是放在任何类或模块,因为我不知道你打算如何开始parsing的联系人。

# 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 

我在我的一个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,它将处理file upload并将其保存到适当的位置。 我用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 

在这里和这里阅读“电子表格”库。 您可以进行适当的改进,并使技术在Rails 3中工作。希望这有助于。