ruby-on-rails – 如何在Rails中上传和解析Excel文件?

我想能够上传包含联系信息的Excel文件.然后我可以解析它,并为我的联系人模型创建记录.

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

我正在使用纸夹宝石在英雄,我已经能够解析vim卡到联系人模型,并寻找类似的东西,但将通过Excel文件的所有行.

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

解决方法

电子表格是迄今为止我发现的最好的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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...