29
30

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.

RubyでExcelファイルをCSVの様に読み込む

Last updated at Posted at 2014-09-20

集計したいデータがExcel形式で提供されることがある。
数が少なければExcelやLibreOfficeなどでCSVに変換してから扱えばよいが、ファイル数が多いと面倒。

Excelファイルの読み込みだけで書き込みがない、しかもRubyで扱うなら、excel2csv-ruby が便利。
ExcelファイルをCSVのように読み込むことができる。

インストール

gemで簡単にインストールできる

gem install excel2csv

もちろん、次の様にGemfileを作って、Bundlerを使っても良い。

gem 'excel2csv'

基本的な使い方

次の様なExcelファイルを読み込むには

sample_xlsx.png

次のようにforeachメソッドで行ごとに読むことができる。

require 'excel2csv'

def read_excel(filename)
  Excel2CSV.foreach(filename) do |row|
    p row
  end
end

read_excel 'sample.xlsx'

実行結果は次の通り。

["cell-A1", "cell-B1", "cell-C1", "cell-D1"]
["cell-A2", "cell-B2", "cell-C2", "cell-D2"]
["cell-A3", "cell-B3", "cell-C3", "cell-D3"]

結合したセルや複数シートも読める

次の様にセルを結合したファイルも読み込める。

sample2_xlsx.png

結合されたセルは左上のセルに値が入っているものとして扱われ、実行した結果は次の様になる。

["cell-A1", "cell-B1", nil,       nil]
["cell-A2", "cell-B2", "cell-C2", "cell-D2"]
["cell-A3", nil,       "cell-C3", "cell-D3"]
[nil,       nil,       "cell-C4", "cell-D4"]

複数のシートがある場合、デフォルトでは1シート目を読むが、foreach メソッドに sheet オプションで指定することで2シート目以降も読むことができる。
次の例は 2シート目を読みこむ例。

require 'excel2csv'

def read_excel(filename)
  Excel2CSV.foreach(filename, sheet:1) do |row|
    p row
  end
end

read_excel 'sample.xlsx'

また、例では xlsx 形式のファイルを使っているが、xls ファイルも問題なく読み込める。

29
30
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
29
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?