小编Jun*_*aid的帖子

如何在Roo(Rails)中编码csv文件:UTF-8中的无效字节序列

我试图上传一个csv文件,但在UTF-8错误中获得无效的字节序列.我正在使用'roo'宝石.

我的代码是这样的:

def upload_results_csv file

    spreadsheet = MyFileUtil.open_file(file)
    header = spreadsheet.row(1) # THIS LINE RAISES THE ERROR

    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      ...
      ...
end

class MyFileUtil

  def self.open_file(file)
    case File.extname(file.original_filename)
      when ".csv" then
        Roo::Csv.new(file.path,csv_options: {encoding: Encoding::UTF_8})
      when ".xls" then
        Roo::Excel.new(file.path, nil, :ignore)
      when ".xlsx" then
        Roo::Excelx.new(file.path, nil, :ignore)
      else
        raise "Unknown file type: #{file.original_filename}"
    end
  end

end.
Run Code Online (Sandbox Code Playgroud)

我不知道如何编码csv文件.请帮忙!

谢谢

ruby csv encoding ruby-on-rails-3

8
推荐指数
1
解决办法
3406
查看次数

标签 统计

csv ×1

encoding ×1

ruby ×1

ruby-on-rails-3 ×1