Class: FastXlsToHash::ParseXls

Inherits:
Object
  • Object
show all
Defined in:
lib/fast_xls_to_hash/xls/parse.rb

Constant Summary collapse

FORMULA_ERROR =
'Error'

Class Method Summary collapse

Class Method Details

.to_hash(file) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/fast_xls_to_hash/xls/parse.rb', line 9

def self.to_hash(file)
  book = Spreadsheet.open(file)

  hash = Hash.new{ |hash, key| hash[key] = {} }
  book.worksheets.each do |sheet|
    sheet.each_with_index do |row, row_index|
      hash[sheet.name.to_sym]["row_#{row_index + 1}".to_sym] = {}
      row.each_with_index do |val, index|
        if val.class == Spreadsheet::Formula
          if val.value.class == Spreadsheet::Excel::Error
            hash[sheet.name.to_sym]["row_#{row_index + 1}".to_sym]["column_#{index + 1}".to_sym] = FORMULA_ERROR
            next
          end
          hash[sheet.name.to_sym]["row_#{row_index + 1}".to_sym]["column_#{index + 1}".to_sym] = val.value
        else
          hash[sheet.name.to_sym]["row_#{row_index + 1}".to_sym]["column_#{index + 1}".to_sym] = val
        end
      end
    end
  end

  kill(book)

  hash
end