本帖是上篇
[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的資料格式不能處理的時候,或者資料格式不符合時
使用者定義資料類型
在使用這個插件的時候,允許導入的字段指向Ruby對象,例如,下面的例子,可以增加一個字段表示上面導入Product的類型情況