ruby on rails 使用fasterCSV将csv文件导入到数据库

在ruby on rails中
使用fasterCSV解析csv文件比标准库的csv要快10倍左右
不过的先安装fasterCSV ,使用gem来安装
gem install fastercsv 

如果是使用工具aptana开发的话,可以用名叫RubyGems的View窗口安装
这个例子是通过上传一个csv来解析csv文件
view层
index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
        <title>Untitled Document</title>
    </head>
    <body>
        <% form_for :dump, :url=>{:controller=>"customer_information", :action=>"csv_import"}, :html => { :multipart => true } do |f| -%>
        <table>
            <tr>
                <td>
                    <label for=”dump_file”>
                        Select a CSV File :
                    </label>
                </td>
                <td>
                    <%= f.file_field :file -%>
                </td>
            </tr>
            <tr>
                <td colspan=’2′>
                    <%= submit_tag 'Submit' -%>
                </td>
            </tr>
        </table>
        <% end -%>
    </body>
</html>

csv_import
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
		<title>Untitled Document</title>
	</head>
	<body>
		OK!!!
	</body>
</html>

controller层
class CustomerInformationController < ApplicationController
  require 'faster_csv'
  
  def csv_import 
      n=0
      FasterCSV.parse(params[:dump][:file],:headers=>true)do |row|
      c=CustomerInformation.new
     
      c.name= row[0]
      c.email = row[1]
      c.remark = row[2]
      if c.save
        n=n+1
        GC.start if n%50==0
      end
      flash.now[:message]="CSV Import Successful,  #{n} new records added to data base"
    end
 end
end

这个例子是参考自
关于fasterCSV http://anw.stikipad.com/ocean/show/FasterCSV
关于CSV http://privacystart.info/index.php?hl=f5&q=uggc%3A%2F%2Ffngvfubaenvyf.jbeqcerff.pbz%2F2007%2F07%2F18%2Fubj-gb-vzcbeg-pfi-svyr-va-envyf%2F

你可能感兴趣的:(c,Ruby,aptana,Rails,rubygems)