0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RubyでBOM付UTF-8のCSV(Excelで直接読めるCSV)を出力する方法

Last updated at Posted at 2020-04-26

Excelで読み取れるCSV

文字コード UTF-8 のCSVファイルをExcelで開くと、以下のように文字化けする。
image.png

文字化けをさせないためには先頭にBOM(バイトオーダーマーク)を付ける必要がある。

#RubyでBOMを出力するサンプル

bom.rb
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

# BOMを出力する
putc 0xEF
putc 0xBB
putc 0xBF
# CSVを出力する
puts 'ID,名前'
puts '1,山田'
puts '2,田中'
puts '3,坂本'

実行

./bom.rb > excel.csv

とするとExcelで読み込めるCSVファイル(excel.csv)ができる。
image.png

0
0
2

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?