在rails 4 中 使用 CSV 组件来 把csv文件导入到数据库

时间:2021-12-27 20:39:27
class HardWorker
  include Sidekiq::Worker
  require 'CSV'

  def perform(file_path)
        csv_text = File.read(file_path)
        csv = CSV.parse(csv_text, :headers => true)
        csv.each do |row|
            gis_road_link = GisRoadLink.new 
            gis_road_link.no = row["NO"]
            gis_road_link.fno = row["FNO"]
            gis_road_link.tno = row["TNO"]
            gis_road_link.from_name = row["FROM_NAME"]
            gis_road_link.to_name = row["TO_NAME"]
            gis_road_link.name = row["NAME"]
            gis_road_link.cds = row["CDS"]                    
            gis_road_link.r_cds = row["R_CDS"]
            gis_road_link.len = row["LEN"]
            gis_road_link.ldkd = row["LDKD"]
            gis_road_link.jdcdkd = row["JDCDKD"]
            gis_road_link.fjdcdkd = row["FJDCDKD"]
            gis_road_link.rxdkd = row["RXDKD"]
            gis_road_link.jffgdkd = row["JFFGDKD"]
            gis_road_link.zyfgdkd = row["ZYFGDKD"]
            gis_road_link.hxkd = row["HXKD"]
            gis_road_link.f_t = row["F_T"]
            gis_road_link.t_f = row["T_F"]
            gis_road_link.dldj = row["DLDJ"]
            gis_road_link.jsfs = row["JSFS"]
            gis_road_link.fglx = row["FGLX"]
            gis_road_link.gjzyd = row["GJZYD"]
            gis_road_link.r_gjzyd = row["R_GJZYD"]
            gis_road_link.jtxtj = row["JTXTJ"]
            gis_road_link.r_jtxtj = row["R_JTXTJ"]
            gis_road_link.sjcs = row["SJCS"]
            gis_road_link.r_sjcs = row["R_SJCS"]
            gis_road_link.ldtxnl = row["LDTXNL"]
            gis_road_link.r_ldtxnl = row["R_LDTXNL"]
            gis_road_link.ldywhs = row["LDYWHS"]
            gis_road_link.r_ldywhs = row["R_LDYWHS"]
            gis_road_link.szxzq = row["SZXZQ"]
            gis_road_link.szjtxq = row["SZJTXQ"]
            gis_road_link.szjd = row["SZJD"]
            gis_road_link.szzt = row["SZZT"]
            gis_road_link.szfdtz = row["SZFDTZ"]
            gis_road_link.zhgxsj = row["ZHGXSJ"]
            gis_road_link.tpxx = row["TPXX"]
            gis_road_link.spxx = row["SPXX"]

            gis_road_link.version = version
            if gis_road_link.save
                puts ("No是:"+gis_road_link.no.to_s + '的数据导入成功')
            else
                puts ("No是:"+gis_road_link.no.to_s + '的数据导入失败')
            end        
        end
end