Ruby 导入excel 并检查格式

本帖是上篇
[url=http://hlee.iteye.com/admin/blogs/749972]在Rails项目中导入excel 导出excel 实用rails解析excel[/url]的姊妹后继,主要介绍一个导入excel的ruby插件

[size=large]插件importex[/size]


安装

 gem install importex


或者rails plugin用

./script/plugin install git://github.com/ryanb/importex.git


创建基于Importex::Base的类

  require 'importex'
class Product < Importex::Base
column "Name", :required => true
column "Price", :format => /^\d+\.\d\d$/, :required => true
column "Amount in Stock", :type => Integer
column "Release Date", :type => Date
column "Discontinued", :type => Boolean
end



导入excel文件

  Product.import("path/to/products.xls")

不能处理定制的负责excel数据比如有图,
预期第一行是字段名,之后都是数据。

使用导入数据

  products = Product.all
products.first["Discontinued"] # => false


all代表所有的数据, 各个字段作为hash

数据验证和容错处理

当excel的数据格式不能处理的时候,或者数据格式不符合时

begin
Product.import(...)
rescue Importex::ImportError => e
puts e.message
end



用户定义数据类型


在使用这个插件的时候,允许导入的字段指向Ruby对象,例如,下面的例子,可以增加一个字段表示上面导入Product的类型情况


class Category < ActiveRecord::Base
def self.importex_value(str)
find_by_name!(str)
rescue ActiveRecord::RecordNotFound
raise Importex::InvalidCell, "No category with that name."
end
end

class Product < Importex::Base
column "Category", :type => Category
end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值