1
1

RailsでCSV出力機能の実装時にハマったポイント

Last updated at Posted at 2023-10-13

はじめに

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

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1