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

Tim*_* T. 14 excel ruby-on-rails

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

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

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

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

Dan*_*nne 19

Spreadsheet是迄今为止我发现的最好的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
Run Code Online (Sandbox Code Playgroud)


Sye*_*lam 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
Run Code Online (Sandbox Code Playgroud)

有模特上传:

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

  # validations, if any
end
Run Code Online (Sandbox Code Playgroud)

生成一个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
Run Code Online (Sandbox Code Playgroud)

在这里这里阅读"电子表格"库.您可以进行适当的改进,并使该技术在Rails 3中运行.希望这会有所帮助.