我想能够上传包含联系信息的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
原文地址:https://www.jb51.cc/ruby/272619.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。