7
6

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.

PowerShellで作成したCSVがExcelで正常に開けない原因と対策

Last updated at Posted at 2015-05-20

この記事の前提はPowerShell 4.0とExcel 2010です。

PowerSehllで作成したCSVの問題

PowerShellで作成したCSVをExcelで開くと、なぜかカンマの位置でセルが区切られていない状態で開かれてしまいます。

例えばPowerShellで"1,2,3,4,5,6,7,8,9,10" > test.csvを実行して、
test.csvをExcelで開くとセルA1に1,2,3,4,5,6,7,8,9,10と表示されます。

原因はPowerShellの文字コード

PowerShellのデフォルト文字コードはUTF-16 Little Endianですが、どうやらこれが原因のようです。

文字コードを意識せずにPowerShellからテキストファイルを作成するとUTF-16 Little Endianで作成されますが、CSVがUTF-16になっているとExcelで開いた時にカンマで区切られないみたいです。

Excelの不具合ですね。
PowerShellのデフォルト文字コードがUTF-16ってのも問題があると思いますが。

対策

"1,2,3,4,5,6,7,8,9,10" > test.csvのようにリダイレクトした時は文字コードを指定できません。
なのでOut-Fileコマンドレットを使ってUTF-16以外の文字コードを指定します。

UTF-8

PS> "1,2,3,4,5,6,7,8,9,10" | Out-File test_utf8.csv -Encoding utf8

Shift-JIS

PS> "1,2,3,4,5,6,7,8,9,10" | Out-File test_default.csv -Encoding default
7
6
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
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?