Class: LibExcel::Formula

Inherits:
Object
  • Object
show all
Defined in:
lib/libexcel/formula.rb

Overview

Manages a Formula object to be used in a Excel::Worksheet.

Builds an Excel XML formula. The Formula class responds to any class method. Such methods should correspond to their Excel counterparts.

Some Excel formulas that will work are:

  • COUNTA

  • SUM

  • etc.

Examples:

formula = Excel::Formula.counta(:row => 1..2)
# Creates an equivalent formula =COUNTA(1:2)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(equ) ⇒ Formula

Should never be called directly. Creates the Formula object



21
22
23
24
# File 'lib/libexcel/formula.rb', line 21

def initialize(equ)
  @xml = LibXML::XML::Node.new('Cell')
  @xml['ss:Formula'] = equ
end

Instance Attribute Details

#xmlObject (readonly)

Returns the value of attribute xml.



17
18
19
# File 'lib/libexcel/formula.rb', line 17

def xml
  @xml
end

Class Method Details

.method_missing(meth, *args) ⇒ Object

A class method that is a catchall for equation names.



58
59
60
61
62
# File 'lib/libexcel/formula.rb', line 58

def self.method_missing(meth, *args)
  buffer = "=#{meth.to_s.upcase}(#{LibExcel.range(args.first)})"

  self.new(buffer)
end

.node_correct?(node) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
44
45
46
47
# File 'lib/libexcel/formula.rb', line 41

def self.node_correct?(node)
  digit_block = /(\[-?\d+\])?/
  r_d_block = /R#{digit_block}C#{digit_block}/
  function = /=[A-Z]+\(#{r_d_block}:#{r_d_block}\)/

  (node['ss:Formula'] =~ function) != nil
end

.partition(node) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/libexcel/formula.rb', line 49

def self.partition(node)
  digit_block = /(\[-?\d+\])?/
  big_block = /R#{digit_block}C#{digit_block}:R#{digit_block}C#{digit_block}/

  m = big_block.match(node['ss:Formula']).to_a[1..4]
  m.map { |bits| bits.nil? ? nil : bits[1..-2].to_i }
end

Instance Method Details

#/(formula) ⇒ Formula

Creates a new Formula thats references the division of one Formula by another Formula.

Examples:

f1 = Excel::Formula.counta(:row => 1..2)
f2 = Excel::Formula.counta(:row => 1..2)
f1_divided_f2 = f1/f1

Returns:

  • (Formula)

    A new Formula reference



35
36
37
38
39
# File 'lib/libexcel/formula.rb', line 35

def /(formula)
  org_f = self.xml['ss:Formula']
  org_f << '/' << formula.xml['ss:Formula'][1..-1]
  Formula.new(org_f) 
end