Class: Marty::Xl

Inherits:
Object
  • Object
show all
Includes:
Delorean::Model
Defined in:
lib/marty/xl.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(worksheets) ⇒ Xl

Returns a new instance of Xl.



281
282
283
284
285
286
287
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
# File 'lib/marty/xl.rb', line 281

def initialize(worksheets)
  @styles = {}
  @package = Axlsx::Package.new
  wb = package.workbook

  # We got some sort of error if the worksheets is an array
  if worksheets.is_a? Hash
    ws = wb.add_worksheet(name: 'EXCEPTION')
    ws.add_row ['error', worksheets['error']]
    ws.add_row ['backtrace', worksheets['backtrace']]
    return
  end

  raise "expected worksheets array, got: #{worksheets}" unless
    worksheets.is_a?(Array)

  worksheets << ['No data', []] if worksheets.count == 0

  worksheets.each do |opl|
    name, ops, opts = opl

    raise "bad worksheet name: #{name}" unless name.is_a?(String)
    raise "bad worksheet ops: #{ops.inspect}" unless ops.is_a?(Array)
    raise "bad options #{opts}" unless opts.is_a?(Hash) || opts.nil?

    # Remove special characters and truncate sheet name due to Excel
    # limitations.  The following chars are not allowed: []*?:\/
    # axlsx >= 2.1.0 doesn't put underscores in sheet names anymore
    name = name.gsub(/[\[\]\*\?\/\\:]/, '').truncate(31)

    opts = self.class.symbolize_keys(opts || {}, ':')
    widths = opts[:widths] || []
    gridlines = opts[:gridlines] != 0

    ws = wb.add_worksheet(name: name)

    ws.column_widths(*widths) if widths.is_a?(Array) && widths.count > 0
    ws.sheet_view.show_grid_lines = gridlines

    apply_relative_worksheet_ops(ws, ops)
  end
  @package.use_shared_strings = true
end

Instance Attribute Details

#packageObject (readonly)

Returns the value of attribute package.



279
280
281
# File 'lib/marty/xl.rb', line 279

def package
  @package
end

#stylesObject (readonly)

Returns the value of attribute styles.



279
280
281
# File 'lib/marty/xl.rb', line 279

def styles
  @styles
end

Class Method Details

.spreadsheet(worksheets) ⇒ Object



4
5
6
7
8
9
10
11
12
# File 'lib/marty/xl.rb', line 4

def self.spreadsheet(worksheets)
  # hack: axlsx tries to modify its input when sent an empty
  # array!  This fails when we sent it a frozen one => make sure
  # we sent it an unfozen array.
  worksheets = [] if worksheets == []

  xl = Marty::Xl.new(worksheets)
  xl.package
end

.symbolize_keys(obj, sym_str = nil) ⇒ Object

recursive symbolize_keys. FIXME: this belongs in a generic library somewhere.



519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
# File 'lib/marty/xl.rb', line 519

def self.symbolize_keys(obj, sym_str = nil)
  case obj
  when Array
    obj.map { |x| symbolize_keys(x, sym_str) }
  when Hash
    obj.each_with_object({}) do |(key, value), result|
      key = key.to_sym if key.is_a?(String)
      result[key] = symbolize_keys(value, sym_str)
    end
  when String
    (sym_str && obj.starts_with?(sym_str)) ? obj[sym_str.length..-1].to_sym : obj
  else
    obj
  end
end

Instance Method Details

#add_style(style) ⇒ Object



325
326
327
328
329
330
331
332
333
334
335
# File 'lib/marty/xl.rb', line 325

def add_style(style)
  raise 'bad style' unless style.is_a?(Hash) || style.is_a?(Array)

  if style.is_a?(Array)
    style.map do |s|
      styles[s] ||= package.workbook.styles.add_style(s)
    end
  else
    styles[style] ||= package.workbook.styles.add_style(style)
  end
end

#apply_relative_worksheet_ops(ws, ops) ⇒ Object



380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# File 'lib/marty/xl.rb', line 380

def apply_relative_worksheet_ops(ws, ops)
  non_pos = ops.select { |opl| opl[0] != 'pos' }
  ops_pos = ops.select { |opl| opl[0] == 'pos' }
  ops_brd = ops.select { |opl| opl[0] == 'border' }

  if (ops_pos.count > 0)
    # Wrap all non-pos options in a pos option with offset 0, 0:
    pos_00_ops = non_pos.count > 0 ? [['pos', [0, 0], non_pos]] : []
    # Recalculate the offsets of embedded pos opts:
    ops = pos_00_ops + recalc_offsets(ops_pos)
  elsif (ops_brd.count > 0)
    # Wrap the non-pos options in a pos opt with offset 0, 0:
    pos_00_ops = [['pos', [0, 0], non_pos]]
    ops = pos_00_ops
  end

  rows, styles, row_styles, format, borders, images = [], [], [], [], [], []
  ops.each do |opl|
    raise "bad op #{opl}" unless opl.length > 1

    case opl[0]
    when 'pos'
      op, offset, data = opl
      raise "bad offset #{offset}" unless
        offset.is_a?(Array) && offset.length == 2 &&
        offset.all? { |x| x.is_a? Integer }

      # column offset, row offset:
      column_offset, row_offset = offset
      r_number, last_row = row_offset, row_offset

      data.each do |d|
        raise "non array data #{d[1]}" unless d[1].is_a?(Array)
        raise "non hash data options #{d[2]}" unless
          [NilClass, Hash, String, Array].member? d[2].class

        case d[0]
        when 'row'
          position_row(d, column_offset, r_number, rows, styles, row_styles)
          last_row = r_number
          r_number += 1
        when 'conditional_formatting', 'merge'
          position_elem(d, offset, last_row, format)
        when 'border'
          position_elem(d, offset, last_row, borders)
        when 'image'
          position_elem(d, offset, last_row, images)
        else
          raise "unknown op #{d[0]} embedded in 'position' option"
        end
      end

    when 'row'
      op, data, options = opl

      raise "bad row op #{opl}" unless data.is_a?(Array) || opl.length > 3
      raise "non hash options #{options} for row" unless
        options.nil? || options.is_a?(Hash)

      options = self.class.symbolize_keys(options || {}, ':')

      options[:style] = add_style(options[:style]) if options[:style]

      ws.add_row data, options

    when 'row_style'
      op, row_num, style = opl

      # FIXME: need to handle Array?
      raise 'non hash arg for row_style' unless style.is_a?(Hash)
      raise "bad row num #{opl}" unless row_num.is_a?(Integer)

      style = self.class.symbolize_keys(style, ':')

      style_id = add_style(style)
      row = ws.rows[row_num]

      row.style = style_id

    when 'merge'
      op, range = opl

      raise "bad merge op #{opl}" unless opl.length == 2

      range = intern_range(ws, range)

      ws.merge_cells range
    when 'conditional_formatting'
      op, range, format = opl

      raise 'non hash arg for format' unless format.is_a?(Hash)

      range = intern_range(ws, range)

      format = self.class.symbolize_keys(format, ':')

      color_scale_a = format[:color_scale]

      if color_scale_a
        raise 'color_scale must be an array' unless
          color_scale_a.is_a?(Array)

        raise 'non-hash color_scale element' unless
          color_scale_a.all? { |x| x.is_a?(Hash) }

        format[:color_scale] = Axlsx::ColorScale.new(*color_scale_a)
      end

      dxfid = format[:dxfId]
      format[:dxfId] = add_style(dxfid) if dxfid.is_a?(Hash)

      ws.add_conditional_formatting(range, format)
    when 'image'
      op, range, img = opl
      raise "bad image params #{range}" unless
        range.is_a?(Array) && range.length == 6

      x1, y1, x2, y2, w, h = range
      raise "bad image range, width or height #{range}" unless
        [x1, y1, w, h].all? { |x| x.is_a? Integer }

      ws.add_image(image_src: "#{Rails.public_path}/images/#{img}",
                   noSelect: true,
                   noMove: true) do |image|
        image.width  = w
        image.height = h
        image.start_at x1, y1
        image.end_at x2, y2 if x2.is_a?(Integer) && y2.is_a?(Integer)
      end
    else
      raise "unknown op #{opl[0]}"
    end
  end
  worksheet_rows(ws, rows, styles, row_styles, format, borders, images) unless
    [ops_pos.count, ops_brd.count].all? { |a| a == 0 }
end

#bordered_cells(a, b) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/marty/xl.rb', line 56

def bordered_cells(a, b)
  a.each_index do |c|
    a[c] = merge_cell_edges(b[c], deep_copy(a[c])) if a[c] && b[c]
    b[c] = a[c] unless a[c].nil?
  end
  b.each_index { |el| b[el] = {} unless b[el] }
end

#deep_copy(value) ⇒ Object



14
15
16
17
18
19
# File 'lib/marty/xl.rb', line 14

def deep_copy(value)
  return value.each_with_object({}) { |(k, v), h| h[k] = deep_copy(v) } if
    value.is_a?(Hash)

  value.is_a?(Array) ? value.map { |v| deep_copy(v) } : value
end

#intern_range(ws, range) ⇒ Object



337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/marty/xl.rb', line 337

def intern_range(ws, range)
  return range if range.is_a? String
  raise "bad range #{range}" unless range.is_a?(Array) && range.length == 4

  x1, y1, x2, y2 = range

  y1, y2 = [y1, y2].map do |y|
    next y unless y.is_a?(Hash)
    raise "bad offset #{y}" unless y['off'].is_a?(Integer)

    ws.rows.last.row_index + y['off']
  end

  [x1, y1, x2, y2].each do |x|
    raise "bad range point #{x}" unless x.is_a? Integer
  end
  Axlsx.cell_r(x1, y1) + ':' + Axlsx.cell_r(x2, y2)
end

#merge_cell_edges(a, b) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/marty/xl.rb', line 21

def merge_cell_edges(a, b)
  return b unless a.kind_of?(Hash) && b.kind_of?(Hash)

  a_border, b_border = a[:border], b[:border]

  return b unless a_border.is_a?(Hash) && a_border[:edges].is_a?(Array)

  non_match = a_border.detect do |key, value|
    key != :edges && b_border[key] != value
  end

  a_border[:edges].each do |edge|
    unless b_border[:edges].include? edge
      # add new edges:
      b_border[:edges] << edge

      # add new style/color for the new edge if there is no style
      # match with the old edges:
      b["border_#{edge}".to_sym] = a_border.each_with_object({}) do |(key, value), h|
        h[key] = value unless key == :edges
      end if non_match
    end
  end
  b
end

#merge_row_edges(a, b) ⇒ Object



47
48
49
50
51
52
53
54
# File 'lib/marty/xl.rb', line 47

def merge_row_edges(a, b)
  return b unless a.count > 0

  a.each_index do |ind|
    b[ind] = merge_cell_edges(a[ind], deep_copy(b[ind]))
  end
  b
end

#position_borders(borders) ⇒ Object



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/marty/xl.rb', line 146

def position_borders(borders)
  b_styles = []
  borders.each do |b|
    top_row, middle_row, bottom_row, edge_h = [], [], [], {}
    br, range, defaults = b
    col0, row0, colw, rowh = range

    raise "wrong border range #{range}" if
      col0 > colw || row0 > rowh || (col0 == colw && row0 == rowh)

    defaults = self.class.symbolize_keys(defaults, ':')

    boxborders = Hash.new do |hash, key|
      hash[key] = {
        border: defaults.merge(edges: key.to_s.split('_').map(&:to_sym))
      }
    end

    boxborders[:nil] = {}

    tro, mro, bro =
      top_row.object_id, middle_row.object_id, bottom_row.object_id

    if col0 == colw
      # vertical line
      edge_h[tro], edge_h[mro], edge_h[bro] =
        ['left'], ['left'], ['left']
    elsif row0 == rowh
      # horizontal line
      edge_h[tro], edge_h[mro], edge_h[bro] =
        ['top'] * 3, ['top'] * 3, ['top'] * 3
    else
      # box
      edge_h[tro] = ['top_left', 'top_right', 'top']
      edge_h[mro] = ['left', 'right', 'nil']
      edge_h[bro] = ['bottom_left', 'bottom_right', 'bottom']
    end

    [top_row, middle_row, bottom_row].each do |r|
      if col0 == colw
        r[col0] = boxborders[edge_h[r.object_id][0].to_sym]
      else
        (col0...colw).each do |counter|
          a = (counter == col0) ? boxborders[edge_h[r.object_id][0].to_sym] : {}

          # counter == col0 == (colw - 1) => merge the edges:
          a = boxborders[edge_h[r.object_id][1].to_sym] =
            merge_cell_edges(a, deep_copy(boxborders[edge_h[r.object_id][1].to_sym])) if
            counter == (colw - 1)

          a = boxborders[edge_h[r.object_id][2].to_sym] unless
            counter == col0 || counter == (colw - 1)

          r[counter] = a
        end
      end
    end

    if row0 == rowh
      b_styles[row0] ||= []
      bordered_cells(top_row, b_styles[row0])
    else
      (row0...rowh).each_with_index do |r, i|
        b_styles[r] ||= []

        a = i == 0 ? top_row : []

        a = merge_row_edges(a, bottom_row) if
          i == (rowh - row0 - 1)

        a = middle_row unless
          i == 0 || i == (rowh - row0 - 1)

        bordered_cells(a, b_styles[r])
      end
    end
  end

  b_styles
end

#position_elem(d, offset, last_row, el) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/marty/xl.rb', line 106

def position_elem(d, offset, last_row, el)
  x1, y1, x2, y2, w, h = d[1]
  column_offset, row_offset = offset

  y_coords = y2.is_a?(Integer) || d[0] != 'image' ? [y1, y2] : [y1]
  x_coords = x2.is_a?(Integer) || d[0] != 'image' ? [x1, x2] : [x1]

  # add the row offset:
  y1, y2 = y_coords.map do |y|
    if y.is_a?(Integer)
      row_offset + y
    elsif y.is_a?(Hash) && y['off'].is_a?(Integer)
      last_row + y['off']
    else
      raise "bad offset #{y}"
    end
  end

  # add the column offset:
  x1, x2 = x_coords.map do |x|
    raise "bad range point #{x}" unless x.is_a? Integer

    column_offset + x
  end

  el[last_row] = [] unless
    el[last_row] || ['border', 'image'].member?(d[0])

  case d[0]
  when 'conditional_formatting'
    el[last_row] << [d[0], [x1, y1, x2, y2], d[2]]
  when 'merge'
    el[last_row] << [d[0], [x1, y1, x2, y2]]
  when 'border'
    el << [d[0], [x1, y1, x2, y2], d[2]]
  when 'image'
    el << [d[0], [x1, y1, x2, y2, w, h], d[2]]
  end
end

#position_row(d, column_offset, r_number, rows, styles, row_styles) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/marty/xl.rb', line 64

def position_row(d, column_offset, r_number, rows, styles, row_styles)
  rows[r_number] ||= []
  styles[r_number] ||= []
  row_styles[r_number] ||= {}

  new_row, new_style = rows[r_number], styles[r_number]

  (0...column_offset).each do |t|
    new_row[t] ||= ''
    new_style[t] ||= {}
  end

  d[1].each_index do |c_index|
    new_row[c_index + column_offset] = d[1][c_index]
  end if d[1].kind_of?(Array)

  if (d.length > 2) && d[2].kind_of?(Hash) && d[2]['style'].kind_of?(Array)
    d[2]['style'].each_index do |c_index|
      new_style[c_index + column_offset] = d[2]['style'][c_index]
    end
  end

  # apply style for the row as a whole:
  if (d.length > 2) && d[2].kind_of?(Hash)
    d[2].each do |key, value|
      if key == :style.to_s
        # skip if the style is an array: /style as an array is
        # handled by the 'apply a style to each cell' section/
        next unless value.kind_of?(Hash)

        d[1].length.times do |t|
          new_style[t + column_offset] = value
        end
      else
        row_styles[r_number][key] = value
      end
    end
  end
  # row data, style:
  rows[r_number], styles[r_number] = new_row, new_style
end

#recalc_offsets(ops_pos) ⇒ Object



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/marty/xl.rb', line 356

def recalc_offsets(ops_pos)
  new_ops1, new_ops2, new_ops = [], [], []
  # precalculate the offsets of pos options embedded in another pos opt:
  ops_pos.each do |d|
    new_ops1 += d[2].select do |inner_ops|
      inner_ops if inner_ops[0] == 'pos'
    end.map do |inner|
      [inner[0], d[1].zip(inner[1]).map { |x, y| x + y }, inner[2]]
    end
  end
  # keep the offsets of non-pos options embedded in pos opt:
  new_ops2 = ops_pos.map do |d|
    [d[0], d[1], d[2].select { |inner| inner if inner[0] != 'pos' }]
  end
  new_ops = new_ops1 + new_ops2
  count = new_ops.count do |d|
    d[2].count do |inner_ops|
      inner_ops if inner_ops[0] == 'pos'
    end > 0
  end

  count == 0 ? new_ops.sort : recalc_offsets(new_ops)
end

#worksheet_rows(ws, rows, styles, row_styles, format, borders, images) ⇒ Object



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/marty/xl.rb', line 227

def worksheet_rows(ws, rows, styles, row_styles, format, borders, images)
  wsrows = []

  b_styles = position_borders(borders)
  rlenmax = rows.map { |el| el.kind_of?(Array) ? el.length : 0 }.max

  rows.each_with_index do |r, index|
    rlen = r.kind_of?(Array) ? r.length : 0

    if rlen < rlenmax
      rows[index] ||= []
      rows[index] += [''] * (rlenmax - rlen)
    end

    row_styles[index] ||= {}

    rsi = row_styles[index]

    rsi['style'] = styles[index].kind_of?(Array) ? styles[index] : []

    if b_styles[index].kind_of?(Array) && b_styles[index].count > 0
      len = [rsi['style'].count, b_styles[index].count].max

      len.times do |ind|
        b_styles[index][ind] ||= {}
        rsi['style'][ind] ||= {}

        rsi['style'][ind] =
          rsi['style'][ind].merge(b_styles[index][ind])
      end

      rsi['style'] = rsi['style'].map { |x| x || {} }
    end

    wsrows << ['row', rows[index], rsi]

    if format[index] && format[index].kind_of?(Array)
      format[index].each do |f|
        raise "wrong number of arguments for #{f[0]}" unless
          [
            ['conditional_formatting', 3],
            ['merge', 2]
          ].member?([f[0], f.length])

        wsrows << f
      end
    end
  end

  apply_relative_worksheet_ops(ws, wsrows + images)
end