本帖是上篇
[url=http://hlee.iteye.com/admin/blogs/749972]在Rails项目中导入excel 导出excel 实用rails解析excel[/url]的姊妹后继,主要介绍一个导入excel的ruby插件
[size=large]插件importex[/size]
安装
或者rails plugin用
创建基于Importex::Base的类
导入excel文件
不能处理定制的负责excel数据比如有图,
预期第一行是字段名,之后都是数据。
使用导入数据
all代表所有的数据, 各个字段作为hash
数据验证和容错处理
当excel的数据格式不能处理的时候,或者数据格式不符合时
用户定义数据类型
在使用这个插件的时候,允许导入的字段指向Ruby对象,例如,下面的例子,可以增加一个字段表示上面导入Product的类型情况
[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