rails中使用fasterCSV解析csv文件比标准库的csv要快10倍左右
先安装fasterCSV
gem install fastercsv
[b]Views:[/b]
[color=red]index.rhtml[/color]
<% form_for :myform, :url=>{:controller=>"users", :action=>"import"}, :html => { :multipart => true } do |f| -%>
Select a CSV File :<%= f.file_field :file -%>
<%= submit_tag 'Submit' -%>
<% end -%>
[color=red]import.rhtml[/color]
<font color=red>OK!!!</font>
[b]Controller:[/b]
[color=red]import[/color]
require 'faster_csv'
def import
n=0
FasterCSV.parse(params[:myform][:file],:headers=>true)do |row|
user = User.new
user.username = row[0]
user.password = row[1]
user.save!
n=n+1
GC.start if n%50==0 #GC 是Rails 的垃圾收集器的类(Garbage Collector,GC)
flash.now[:notice]="CSV Import Successful, #{n} new records added to data base"
end
end
# :headers=>true 的意思是第一行存在行头,不导入数据库