Rails rails FasterCsv 文件导入问题

spiderxu · June 05, 2014 · Last by spiderxu replied at June 05, 2014 · 2312 hits

今天做 csv 导入的时候遇到一个问题,哪位大神帮忙看下 以前 ruby 1.9 版本以下的时候我导入CSV文件都是这样写的

require 'csv'

FasterCSV.foreach(file_path) do |row|
   block
end

这样轻轻松松就导进来了,但是现在2.0 版本的时候,再用这种方法导入的时候就悲剧了 出现下面问题

please switch to Ruby 1.9's standard
CSV library.  It's FasterCSV plus
support for Ruby 1.9's m17n encoding
engine.

在网上搜了一下原因,发现有大神回答了这个问题 http://stackoverflow.com/questions/5011395/what-is-ruby-1-9-standard-csv-library

查了一下文档,CSV parse 的用法有一段文字 http://www.ruby-doc.org/stdlib-2.1.2/libdoc/csv/rdoc/CSV.html#method-c-parse This method can be used to easily parse CSV out of a String. You may either provide a block which will be called with each row of the String in turn 大概意思是 parse 方法只接收一个字符串,我要写一个 block 将数据转化成字符串,不知道有没有理解错,或者大家有没有更好的办法 求大神指教。

我好像明白什么意思了,在使用 parse 前使用 File.open 将文件读取出来

File.open(file_name)  do |f|
  csv = f.read 
  row = CSV.parse(csv)
end

应该是上面的意思。

You need to Sign in before reply, if you don't have an account, please Sign up first.