0

我需要在 ruby​​ 中读取外部文件。在本地运行file -i节目 text/plain; charset=utf-16le

我用分隔符 '\t' 在 ruby​​ CSV 中打开它,一行显示为: <CSV::Row "\xFF\xFEC\x00a\x00n\x00d\x00i\x00d\x00a\x00t\x00e\x00 \x00n\x00u\...

row.to_s 产生\x000\x000\x000\x001\x00\t\x00E\x00D\x00O

运行puts row正确显示数据: 0001 EDOARDO A...(这些值也在 vim 和 LibreOffice Calc 中清晰显示)

任何建议如何在 ruby​​ 中获取数据?我尝试了各种打开 CSV 的组合external_encoding: 'utf-16le', internal_encoding: "utf-8"等,但puts它是唯一能提供清晰价值的东西

它还在 ruby​​ CSV 中表示 ASCII-8BIT。 <#CSV io_type:StringIO encoding:ASCII-8BIT lineno:0 col_sep:"\\t" row_sep:"\n" quote_char:"\"" headers:true>

该文件本身是作为 XLS 文件生成的。我在这里上传了一个编辑过的版本(在 gvim 上编辑过)

4

2 回答 2

1

这对我来说很好用:

require 'csv'

CSV.foreach("file.xls", encoding: "UTF-16LE:UTF-8", col_sep: "\t") do |row|
  puts row.inspect
end

这将产生以下输出:

["Candidate number", "First name", "Last name", "Date of birth", "Preparation centre", "Result", "Score", "Reading and Writing", "Listening", "Speaking", "Result enquiry", "Raised on", "Raised by", "Enquiry status", "Withdrawn on", "Withdrawn by", nil]
["0001", "EDOARDO", "AGNEW", "20/01/2001", "Fondazione Istituto Massimo", "RY5-G8-Y2", "-", nil, nil, nil, "-", "00000000", nil, nil, "00000000", nil, nil]

如您所见,每一行都是文档中每一列的字符串数组。

于 2019-05-11T18:21:43.970 回答
0

问题是我正在阅读回形针附件,该附件需要在保存之前设置编码(覆盖)。

在模型中添加 s3_headers 有效:

 has_attached_file :attachment, s3_headers: lambda { |attachment|
                                  { 
                                    'content-Type' => 'text/csv; charset=utf-16le'
                                  }
                                }

感谢 Julien 告诉我这个问题与回形针附件有关(该解决方案可以直接读取文件)

于 2019-05-13T16:03:04.273 回答