10
12

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でエクセルを操る方法(roo、roo-xls)

Last updated at Posted at 2017-12-05

Rubyでエクセルを操作するには、色々なgemがあるそうです。
私が今回使ったのはrooというgem

準備

irb> require 'roo'
=> true

irb> Roo::Spreadsheet.open("2.xlsx")

これだけ!!

使い方

# シート名取得
irb> file.sheets
=> ["112", "113"]

# 112シートの1行目
irb> file.sheet('112').row(1)

# 112シートの1行目の1列目
irb> file.sheet('112').row(1)[0]

# シートで繰り返し
irb> file.each_with_pagename do |name, sheet|
irb>  name # シート名
irb>  sheet.row(1)[0] # 対象のシートの1行目の1列目
irb> end

落とし穴1(.xlsは使えない)

で、ここまで来て落とし穴がありまして.xlsファイルだと上手くいかない。

irb> file = Roo::Spreadsheet.open("1.xls")

ArgumentError: Can't detect the type of 1.xls - please use the :extension option to declare its type.

オプション付けろ!みたいな感じだから、色々調べると

irb> file = Roo::Spreadsheet.open('1.xls', extension: :xls)

ArgumentError: Can't detect the type of 1.xls - please use the :extension option to declare its type.

あーよくわからないけど、ダメじゃこりゃってなった。
けど、よくよく調べるとroo-xlsってのがある

irb> require 'roo-xls'
=> true

irb> file = Roo::Spreadsheet.open("1.xls", extension: :xls)

=> <#Roo::Excel:1775230432073564 @filename @workbook @options @cell @cell_type @cells_read @first_row @last_row @first_column @last_column @header_line @formula @fonts>

irb> file.sheets
=> ["112", "113"]

irb> file.sheet(0).row(0)
=> [, ]

使い方は、今の所全く同じでいけそうだ。

落とし穴2(型がおかしくなる)- 未解決!

ただし! なんか変な動きするので共有しておく

日付がセルによって数値になる

# 2014/12/31
irb> file.sheet(1).row(1)[0]
=> #<Date: 2014-12-31 ((2457023j,0s,0n),+0s,2299161j)>
irb > file.sheet(1).row(1)[0].class
=> Date

# 2014/12/01
> file.sheet(1).row(2)[0]
=> 41974.0
> file.sheet(1).row(2)[0].class
=> Float

数値がセルによってFloatになる

# 112
> file.sheet(1).row(3)[0]
=> 112.0
> file.sheet(1).row(3)[0]
=> Float

困っております...

10
12
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
10
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?