Rails导入CSV由于格式错误而失败 [英] Rails importing CSV fails due to mal-formation

查看:166
本文介绍了Rails导入CSV由于格式错误而失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用以下代码导入文件时,得到CSV:MalFormedCSVError:

I get a CSV:MalFormedCSVError when I try to import a file using the following code:

  def import_csv(filename, model)
    CSV.foreach(filename, :headers => true) do |row|
      item = {}
      row.to_hash.each_pair do |k,v|
          item.merge!({k.downcase => v})
      end
        model.create!(item)
    end
  end

csv文件很大,有没有办法我可以记录格式错误的行和继续执行以及其余的csv文件?

The csv files are HUGE, so is there a way I can just log the bad formatted lines and CONTINUE EXECUTION with the remainder of the csv file?

推荐答案

您可以尝试处理自己读取的文件,并让CSV一次只工作一行.像这样:

You could try handling the file reading yourself and let CSV work on one line at a time. Something like this:

File.foreach(filename) do |line|
  begin
    CSV.parse(line) do |row|
      # Do something with row...
    end
  rescue CSV::MalformedCSVError => e
    # complain about line
  end
end

您当然必须自己对标题行做些事情.另外,如果您在CSV中嵌入了换行符,则此操作将无效.

You'd have to do something with the header line yourself of course. Also, this won't work if you have embedded newlines in your CSV.

这篇关于Rails导入CSV由于格式错误而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆