Class: FruitToLime::RooHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/fruit_to_lime/roo_helper.rb

Overview

Examples:

transform xlsx file into rows

organizations_path = File.join(File.dirname(__FILE__), 'organizations.xlsx') # same path as this file
rows = FruitToLime::RooHelper.new(Roo::Excelx.new(organizations_path)).rows

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ RooHelper

Returns a new instance of RooHelper.



8
9
10
11
# File 'lib/fruit_to_lime/roo_helper.rb', line 8

def initialize(data)
    @data = data
    @default_sheet = data.sheets.first
end

Instance Method Details

#cell_to_csv(row, col, sheet) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/fruit_to_lime/roo_helper.rb', line 44

def cell_to_csv(row, col, sheet)
    if @data.empty?(row,col,sheet)
        ''
    else
        onecell = @data.cell(row,col,sheet)
        case @data.celltype(row,col,sheet)
        when :string
            unless onecell.empty?
                onecell.encode('UTF-8').strip
            end
        when :float, :percentage
            if onecell == onecell.to_i
              onecell.to_i.to_s
            else
              onecell.to_s
            end
        when :date, :datetime
            onecell.to_s
        when :time
            Roo::Base.integer_to_timestring(onecell)
        when :formula
            onecell.to_s
        else
            raise "unhandled celltype #{@data.celltype(row,col,sheet)} for cell at row: #{row}, col: #{col} in sheet #{sheet}"
        end || ""
    end
end

#rowsObject

Get rows for the first sheet. The rows are hashes of the first row of cells as header cells and the rest as content.

Examples:

If the header ‘Name’ and the second column contains ‘Johan’.

FruitToLime::RooHelper.new(Roo::Excelx.new(file_path)).rows
# returns:
[{'Name'=>'Johan'}]


19
20
21
# File 'lib/fruit_to_lime/roo_helper.rb', line 19

def rows
    return rows_for_sheet(@default_sheet)
end

#rows_for_sheet(sheet) ⇒ Object

Examples:

transform xlsx file into rows for the second sheet

data = Roo::Excelx.new(organizations_path)
rows = FruitToLime::RooHelper.new(data).rows_for_sheet(data.sheets[1])


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/fruit_to_lime/roo_helper.rb', line 26

def rows_for_sheet(sheet)
    column_headers = {}
    1.upto(@data.last_column(sheet)) do |col|
        column_headers[col] = @data.cell(1, col, sheet).encode('UTF-8')
    end

    rs = []
    2.upto(@data.last_row(sheet)) do |row|
        r = {}
        1.upto(@data.last_column(sheet)) do |col|
            val = cell_to_csv(row, col, sheet)
            r[column_headers[col]] = val
        end
        rs.push(r)
    end
    return rs
end