简体   繁体   中英

Exporting Ruby CSV from ActiveRecord single quote in Excel looks weird

When I open the exported CSV file from Excel after extracting data from my table using the Ruby's CSV library . I open the file using Excel (all of my users use Excel to open my CSV files). It comes out funky looking. Here's some screen shots.

I tried converting converting it to ASCII, but I get an error: Encoding::UndefinedConversionError: U+2019 from UTF-8 to US-ASCII

CSV.open(fileNameInbound, 'wb', :encoding => Encoding::US_ASCII) do |csv| 
  myModel.all.each do |m| 
    csv << m 
  end 
end

My users are not tech savvy so I cannot have them trying to change it to UTF-8 or something.

In Sublime Text looks like this:

在此处输入图像描述

In Excel looks like this:

在此处输入图像描述

I fixed my problem by adding BOM characters in the beginning of my file to force the UTF-8 in Excel.

CSV.open(fileNameInbound, 'wb', encoding: 'UTF-8') do |csv| 
  myModel.all.each do |m| 
    csv << ['\xef\xbb\xbf']
    csv << m 
  end 
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM