如何在Rails中上传和解析Excel文件?

时间:2011-01-28 06:22:26

标签: ruby-on-rails excel

我希望能够上传包含联系信息的Excel文件。然后我去解析它并为我的Contact模型创建记录。

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

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

简化任务的宝石和要解析的示例代码会很有帮助!

3 个答案:

答案 0 :(得分:18)

电子表格是迄今为止我发现的最好的Excel解析器。它提供了很多功能。

你说你使用Paperclip作为好的附件。但是,如果您将附件存储在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

答案 1 :(得分: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中运行。希望这会有所帮助。

答案 2 :(得分:0)

我制作了一个很容易实现这一目标的宝石。我称之为Parxer和......

  • 它建立在roo gem。
  • 之上
  • 它允许您解析xls,xlsx和csv文件。
  • 有DSL处理:
    • 列映射。
    • 文件,行和列/单元格验证。
    • 列/单元格格式。
相关问题