2
3

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 5 years have passed since last update.

CSVをエクセルでも見れる文字コードUTF-16LE(リトルエンディアン)で出力するメモ

Posted at

UTF-16のBOM(リトルエンディアン)を挿入するワンライナー

ruby -i -e 'print ARGF.read.sub(/\A/, "\u{FFFE#}")' file.csv

UTF-16LEのBOM(リトルエンディアン)を挿入するFileクラス拡張

UTF-8のファイルからUTF-16LEへの変換前提

class File
  def self.insert_bom(input_filename, output_filename)
    src = File.read(input_filename)
    File.open(output_filename, "w:UTF-16") do |f|
      src = '  ' + src
      src.setbyte(0, 0xFF)
      src.setbyte(1, 0xFE)
      f.print src
    end
  end
end

UTF-8のファイルをUTF-16LEに変換する

File.write "file_utf16.csv", NKF.nkf('-w16L',File.read("file_utf8.csv")) 
File.insert_bom("file_utf16.csv", "file_utf16_bom.csv")

実行結果

$ nkf --guess file_utf8.csv
UTF-8 (CRLF)

$ nkf --guess file_utf16.csv
BINARY

$ nkf --guess file_utf16_bom.csv
UTF-16 LE (BOM) (CRLF)

参考

http://magazine.rubyist.net/?0009-BundledLibraries#l7
http://tbpgr.hatenablog.com/entry/20140204/1391517653

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?