はじめに
RailsでCSV出力機能は定番化されているが、少しハマったポイントを整理していく
実装内容
controller
require 'csv'
def export
reports = (APIにリクエストしてデータを取得)
generate_csv(reports)
end
private
def generate_csv(reports)
bom = %w[EF BB BF].map { |e| e.hex.chr }.join
csv_data = CSV.generate(bom, row_sep: "\r\n", force_quotes: true) do |csv|
csv << weekly_reports['header']
weekly_reports['body'].each { |report_body| csv << report_body }
end
filename = "reports_#{Time.current.strftime('%Y%m%d%H%M%S%L')}.csv"
send_data(csv_data, filename:)
end
ハマった点1 CSV出力時のオプション指定
CSV.generate
で引数を指定しないと、文字化けするので、以下を引数に指定
- bom → Byte Order Markの略で、Unicodeで書かれたテキストファイルの先頭に付ける
- row_sep: "\r\n" → 行の区切り文字としてCRLFを使用(Windowsで標準)
- force_quotes: true` → 強制的に二重引用符で囲む。読み取りエラー防止。
それでも文字化けが解消しない。。。
ハマった点2 Mac自体の言語設定を日本語に変更
ちょっとこれは盲点だったが、自分のMACでは言語をあえて「英語」にしていた。
そのため、日本語に戻して、PC再起動したら、無事に文字化けがなくなった。
調査メモ
BOMの指定について
https://exlight.net/devel/unicode/bom.html