ruby-on-rails – 如何在Rails中上传和解析Excel文件?
发布时间:2020-12-16 20:05:03 所属栏目:百科 来源:网络整理
导读:我想能够上传包含联系信息的Excel文件.然后我可以解析它,并为我的联系人模型创建记录. 我的应用程序是一个Rails应用程序. 我正在使用纸夹宝石在英雄,我已经能够解析vim卡到联系人模型,并寻找类似的东西,但将通过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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |