Class: GenericSpreadsheet

Inherits:
Object
  • Object
show all
Defined in:
lib/roo/generic_spreadsheet.rb

Overview

Base class for all other types of spreadsheets

Direct Known Subclasses

Excel, Google, Openoffice

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#default_sheetObject

Returns the value of attribute default_sheet.



4
5
6
# File 'lib/roo/generic_spreadsheet.rb', line 4

def default_sheet
  @default_sheet
end

#header_lineObject

sets the line with attribute names (default: 1)



7
8
9
# File 'lib/roo/generic_spreadsheet.rb', line 7

def header_line
  @header_line
end

Class Method Details

.letter_to_number(letters) ⇒ Object

convert letters like ‘AB’ to a number



259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/roo/generic_spreadsheet.rb', line 259

def self.letter_to_number(letters)
  result = 0
  while letters && letters.length > 0
    character = letters[0,1].upcase
    num = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".index(character)
    raise ArgumentError, "invalid column character '#{letters[0,1]}'" if num == nil
    num += 1
    result = result * 26 + num
    letters = letters[1..-1]
  end
  result
end

.number_to_letter(n) ⇒ Object

convert a number to something like this: ‘AB’



248
249
250
251
252
253
254
255
256
# File 'lib/roo/generic_spreadsheet.rb', line 248

def GenericSpreadsheet.number_to_letter(n)
  letters=""
  while n > 0
    num = n%26
    letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[num-1,1] + letters
    n = n.div(26)
  end
  letters
end

Instance Method Details

#empty?(row, col, sheet = nil) ⇒ Boolean

true if cell is empty

Returns:

  • (Boolean)


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/roo/generic_spreadsheet.rb', line 46

def empty?(row, col, sheet=nil)
  #def excel_empty?(row, col, sheet=nil)
  sheet = @default_sheet unless sheet
  read_cells(sheet) unless @cells_read[sheet] or self.class == Excel
  row,col = normalize(row,col)
  return true unless cell(row, col, sheet)
  return true if celltype(row, col, sheet) == :string && cell(row, col, sheet).empty?
  #false
  #end

  # true if a cell is empty
  #def oo_empty?(row, col, sheet=nil)
  #sheet = @default_sheet unless sheet
  #read_cells(sheet) unless @cells_read[sheet]
  #row,col = normalize(row,col)
  return true if row < first_row(sheet) || row > last_row(sheet) || col < first_column(sheet) || col > last_column(sheet)
  #return true unless cell(row, col, sheet)
  #  return true if celltype(row, col, sheet) == "string" && cell(row, col, sheet) == ""
  #return true if celltype(row, col, sheet) == :string && cell(row, col, sheet) == ""
  false
end

#find(*args) ⇒ Object

find a row either by row number or a condition Caution: this works only within the default sheet -> set default_sheet before you call this method (experimental. see examples in the test_roo.rb file)



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'lib/roo/generic_spreadsheet.rb', line 288

def find(*args) # :nodoc
  result_array = false
  args.each {|arg,val|
    if arg.class == Hash
      arg.each { |hkey,hval|
        if hkey == :array and hval == true
          result_array = true
        end
      }
    end
  }
  column_with = {}
  1.upto(last_column) do |col|
    column_with[cell(@header_line,col)] = col
  end
  result = Array.new
  #-- id
  if args[0].class == Fixnum
    rownum = args[0]
    tmp = {}
    1.upto(self.row(rownum).size) {|j|
      x = ''
      column_with.each { |key,val|
        if val == j
          x = key
        end
      }
      tmp[x] = cell(rownum,j)
    }
    result = [ tmp ] # row(rownum)
    #-- :all
  elsif args[0] == :all
    if args[1].class == Hash
      args[1].each {|key,val|
        if key == :conditions
          column_with = {}
          1.upto(last_column) do |col|
            column_with[cell(@header_line,col)] = col
          end
          conditions = val
          first_row.upto(last_row) do |i|
            # are all conditions met?
            found = 1
            conditions.each { |key,val|
              if cell(i,column_with[key]) == val
                found *= 1
              else
                found *= 0
              end
            }
            # p self.row(i) if found > 0
            if found > 0
              tmp = {}
              1.upto(self.row(i).size) {|j|
                x = ''
                column_with.each { |key,val|
                  if val == j
                    x = key
                  end
                }
                tmp[x] = cell(i,j)
              }
              if result_array
                result << self.row(i)
              else
                result << tmp
              end
            end
          end
        end # :conditions
      }
    end
  end
  result
end

#first_column(sheet = nil) ⇒ Object

returns the number of the first non-empty column



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/roo/generic_spreadsheet.rb', line 227

def first_column(sheet=nil)
  if sheet == nil
    sheet = @default_sheet
  end
  read_cells(sheet) unless @cells_read[sheet]
  if @first_column[sheet]
    return @first_column[sheet]
  end
  impossible_value = 999_999 # more than a spreadsheet can hold
  result = impossible_value
  @cell[sheet].each_pair {|key,value|
    y,x = key.split(',')
    x = x.to_i
    result = [result, x].min if value
  }
  result = nil if result == impossible_value
  @first_column[sheet] = result
  result
end

#first_column_as_letter(sheet = nil) ⇒ Object

first non-empty column as a letter



140
141
142
# File 'lib/roo/generic_spreadsheet.rb', line 140

def first_column_as_letter(sheet=nil)
  GenericSpreadsheet.number_to_letter(first_column(sheet))
end

#first_row(sheet = nil) ⇒ Object

returns the number of the first non-empty row



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/roo/generic_spreadsheet.rb', line 206

def first_row(sheet=nil)
  if sheet == nil
    sheet = @default_sheet
  end
  read_cells(sheet) unless @cells_read[sheet]
  if @first_row[sheet]
    return @first_row[sheet]
  end
  impossible_value = 999_999 # more than a spreadsheet can hold
  result = impossible_value
  @cell[sheet].each_pair {|key,value|
    y,x = key.split(',')
    y = y.to_i
    result = [result, y].min if value
  }
  result = nil if result == impossible_value
  @first_row[sheet] = result
  result
end

#infoObject

Returns information of the spreadsheet document and all sheets within this document.



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/roo/generic_spreadsheet.rb', line 81

def info
  # $log.debug(self.class.to_s+"#info started")
  result = "File: #{File.basename(@filename)}\n"+
    "Number of sheets: #{sheets.size}\n"+
    "Sheets: #{sheets.map{|sheet| sheet+", "}.to_s[0..-3]}\n"
  n = 1
  # $log.debug(sheets.inspect)
  sheets.each {|sheet|
    # $log.debug("Info fuer Sheet=#{sheet}")
    self.default_sheet = sheet
    # $log.debug("nach default_sheet=")
    result << "Sheet " + n.to_s + ":\n"
    unless first_row
      result << "  - empty -"
    else
      result << "  First row: #{first_row}\n"
      result << "  Last row: #{last_row}\n"
      result << "  First column: #{GenericSpreadsheet.number_to_letter(first_column)}\n"
      result << "  Last column: #{GenericSpreadsheet.number_to_letter(last_column)}"
    end
    result << "\n" if sheet != sheets.last
    n += 1
  }
  # $log.debug(self.class.to_s+"#info ended")
  result
end

#last_column(sheet = nil) ⇒ Object

returns the number of the last non-empty column



184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/roo/generic_spreadsheet.rb', line 184

def last_column(sheet=nil)
  # $log.debug("#{self.class.to_s}#last_column(#{sheet})")
  sheet = @default_sheet unless sheet
  read_cells(sheet) unless @cells_read[sheet]
  if @last_column[sheet]
    # $log.debug("last_column of sheet #{sheet} already set")
    return @last_column[sheet]
  end
  # $log.debug("last_column of sheet #{sheet} not yet set")
  impossible_value = 0
  result = impossible_value
  @cell[sheet].each_pair {|key,value|
    y,x = key.split(',')
    x = x.to_i
    result = [result, x].max if value
  }
  result = nil if result == impossible_value
  @last_column[sheet] = result
  result
end

#last_column_as_letter(sheet = nil) ⇒ Object

last non-empty column as a letter



145
146
147
# File 'lib/roo/generic_spreadsheet.rb', line 145

def last_column_as_letter(sheet=nil)
  GenericSpreadsheet.number_to_letter(last_column(sheet))
end

#last_row(sheet = nil) ⇒ Object

returns the number of the last non-empty row



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/roo/generic_spreadsheet.rb', line 165

def last_row(sheet=nil)
  sheet = @default_sheet unless sheet
  read_cells(sheet) unless @cells_read[sheet]
  if @last_row[sheet]
    return @last_row[sheet]
  end
  impossible_value = 0
  result = impossible_value
  @cell[sheet].each_pair {|key,value|
    y,x = key.split(',')
    y = y.to_i
    result = [result, y].max if value
  }
  result = nil if result == impossible_value
  @last_row[sheet] = result
  result
end

#normalize(row, col) ⇒ Object

converts cell coordinate to numeric values of row,col



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/roo/generic_spreadsheet.rb', line 29

def normalize(row,col)
  if row.class == String
    if col.class == Fixnum
      # ('A',1):
      # ('B', 5) -> (5, 2)
      row, col = col, row
    else
      raise ArgumentError
    end
  end
  if col.class == String
    col = GenericSpreadsheet.letter_to_number(col)
  end
  return row,col
end

#open_from_uri(uri) ⇒ Object



149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/roo/generic_spreadsheet.rb', line 149

def open_from_uri(uri)
  require 'open-uri' ;
  tempfilename = File.join(@tmpdir, File.basename(uri))
  f = File.open(tempfilename,"wb")
  begin
    open(uri) do |net|
      f.write(net.read)
    end
  rescue
    raise "could not open #{uri}"
  end
  f.close
  File.join(@tmpdir, File.basename(uri))
end

#reloadObject

reopens and read a spreadsheet document



70
71
72
73
74
75
76
77
# File 'lib/roo/generic_spreadsheet.rb', line 70

def reload
  ds = @default_sheet
  initialize(@filename) if self.class == Openoffice or
    self.class == Excel
  initialize(@spreadsheetkey,@user,@password) if self.class == Google
  self.default_sheet = ds
  #@first_row = @last_row = @first_column = @last_column = nil
end

#remove_tmpObject

recursively removes the current temporary directory this is only needed if you work with zipped files or files via the web



133
134
135
136
137
# File 'lib/roo/generic_spreadsheet.rb', line 133

def remove_tmp
  if File.exists?(@tmpdir)
    FileUtils::rm_r(@tmpdir)
  end
end

#to_csv(filename = nil, sheet = nil) ⇒ Object

write the current spreadsheet to stdout or into a file



273
274
275
276
277
278
279
280
281
282
283
# File 'lib/roo/generic_spreadsheet.rb', line 273

def to_csv(filename=nil,sheet=nil)
  sheet = @default_sheet unless sheet
  if filename
    file = File.open(filename,"w") # do |file|
    write_csv_content(file,sheet)
    file.close
  else
    write_csv_content(STDOUT,sheet)
  end
  true
end

#to_yaml(prefix = {}, from_row = nil, from_column = nil, to_row = nil, to_column = nil, sheet = nil) ⇒ Object

returns a rectangular area (default: all cells) as yaml-output you can add additional attributes with the prefix parameter like: oo.to_yaml(“sheet” => “1”)



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/roo/generic_spreadsheet.rb', line 111

def to_yaml(prefix={}, from_row=nil, from_column=nil, to_row=nil, to_column=nil,sheet=nil)
  sheet = @default_sheet unless sheet
  result = "--- \n"
  (from_row||first_row(sheet)).upto(to_row||last_row(sheet)) do |row|
    (from_column||first_column(sheet)).upto(to_column||last_column(sheet)) do |col|
      unless empty?(row,col,sheet)
        result << "cell_#{row}_#{col}: \n"
        prefix.each {|k,v|
          result << "  #{k}: #{v} \n"
        }
        result << "  row: #{row} \n"
        result << "  col: #{col} \n"
        result << "  celltype: #{self.celltype(row,col,sheet)} \n"
        result << "  value: #{self.cell(row,col,sheet)} \n"
      end
    end
  end
  result
end