---
title: "rails 如何将excel文件导入数据库"
author: "任清宇"
date: "2016-08-31T15:12:03Z"
tags: ["Ruby"]
categories: ["编程语言"]
slug: "rails-excel"
draft: false
lastmod: "2016-08-31T15:14:02Z"
id: 2321866
url: "https://994800477.iteye.com/blog/2321866"
---

有一个小需求，需要一个脚本将excel文件导入数据库对应字段。

     正好可以练习一下task，不过首先先查查有没有什么好gem可以利用下（原谅我这么懒）

     找到一个'roo' 回到gemfile中发现项目中已经包含了这个gem，恩看样子大家都在用，查看了一下用法还是很简单，非常好用。

     

```
# excel
gem 'roo', '~> 2.3.2', require: false
```

    在 gemfile中添加上这个gem

 

    然后创建一个新的rake任务，就可以开始我们的小任务了

    

```
namespace :v5_8_5 do
  task a_change_offer_preferred: :environment do
    require 'roo'  
    file = "#{Rails.root}/tmp/preferred_offers.xlsx" # 将文本路径赋给对象
    if File.exists?(file)
      # 打开文本赋值给xlsx对象，将文本第一列赋值给对象sheet
      xlsx       = Roo::Spreadsheet.open(file, extension: :xlsx)
      sheet      = xlsx.sheet(0)
 
      # 这里将读取出来的数据更新到数据表中
      sheet.each do |row|
        offer = Offer.find_by(id: row[0])
        offer.update_columns(description: row[2], position: row[3])
      end
    end
  end
end
```

   执行 rake v5\_8\_5:a\_change\_offer\_preferred

  就可以进行数据迁移了，当然实际中最好加上log，以及更新容错，捕获异常等级制才显得更加完善。

   怎么样 这个gem是不是很好用，官方文档上还有导入csv 等等很多的方法

   附上链接 https://github.com/roo-rb/roo