Class: Sheet2hash::Workbook
- Inherits:
-
Object
- Object
- Sheet2hash::Workbook
- Defined in:
- lib/sheet2hash.rb
Overview
Sheet2hash::Workbook converts Excel or Spreadsheet into Ruby Hash.
Instance Method Summary collapse
-
#initialize(path, opts = {}) ⇒ Workbook
constructor
Creates a Workbook.
-
#sheet ⇒ String
Returns the name of current sheet.
-
#sheets ⇒ Array
Returns all sheets of this Workbook.
-
#to_a ⇒ Object
Converts current sheet to an Array of Hash.
-
#to_h ⇒ Hash
Converts all sheets to a Hash, sheet names are the keys, values are Array of Hash.
-
#turn_to(sheet, sheet_opts = {}) ⇒ Object
Turns to specified sheet of this Workbook.
Methods included from Options
Constructor Details
#initialize(path, opts = {}) ⇒ Workbook
Creates a Workbook.
16 17 18 19 20 21 |
# File 'lib/sheet2hash.rb', line 16 def initialize path, opts = {} @workbook = Roo::Spreadsheet.open path @opts = opts @sheet_opts = {} set_sheet_attributes end |
Instance Method Details
#sheet ⇒ String
Returns the name of current sheet.
58 59 60 |
# File 'lib/sheet2hash.rb', line 58 def sheet @workbook.default_sheet end |
#sheets ⇒ Array
Returns all sheets of this Workbook.
51 52 53 |
# File 'lib/sheet2hash.rb', line 51 def sheets @workbook.sheets end |
#to_a ⇒ Object
Converts current sheet to an Array of Hash.
77 78 79 80 81 82 83 84 85 |
# File 'lib/sheet2hash.rb', line 77 def to_a ary = [] @rows.each do |row| record = [] @columns.each { |col| record << trim_int_cell(@workbook.cell(row, col)) } ary << Hash[ @header.zip record ] end ary end |
#to_h ⇒ Hash
Converts all sheets to a Hash, sheet names are the keys, values are Array of Hash.
65 66 67 68 69 70 71 72 |
# File 'lib/sheet2hash.rb', line 65 def to_h hash = {} sheets.each do |sheet| turn_to sheet hash[sheet] = to_a end hash end |
#turn_to(sheet, sheet_opts = {}) ⇒ Object
Turns to specified sheet of this Workbook.
34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/sheet2hash.rb', line 34 def turn_to sheet, sheet_opts = {} if sheet.kind_of?(Integer) && sheet <= sheets.size @workbook.default_sheet = sheets[sheet - 1] @sheet_opts = sheet_opts set_sheet_attributes elsif sheet.kind_of?(String) && sheets.include?(sheet) @workbook.default_sheet = sheet @sheet_opts = sheet_opts set_sheet_attributes else raise SheetNotFoundError end end |