Skip to content

Instantly share code, notes, and snippets.

@marcocarvalho
Last active December 21, 2015 21:08
Show Gist options
  • Save marcocarvalho/6366008 to your computer and use it in GitHub Desktop.
Save marcocarvalho/6366008 to your computer and use it in GitHub Desktop.
Excel / SpreedSheet column notation calculator in ruby
#!/usr/bin/env ruby
module Spreedsheet
module ColumnNotation
def seed
@seed ||= ('A'..'Z').to_a
end
def position_to_column_notation(num, minus = 0)
m = num.divmod(seed.size)
if m.first > 0
extr = ''
extr = position_to_column_notation(m.first, 1) if m.first > seed.size
[extr, seed[m.first - 1], seed[m.last - minus]].join('')
else
seed[m.last]
end
end
def column_notation_to_position(str_param)
str = str_param.reverse
val = 0
str.split('').each_with_index do |item, pwr|
power = pwr > 1 ? pwr : 1
plus = pwr == 0 ? 0 : 1
multiplier = pwr == 0 ? 1 : seed.size
val += ( (seed.index(item) + plus) * multiplier ** power )
end
val
end
end
end
class A
include Spreedsheet::ColumnNotation
end
a = A.new
[0, 24, 25, 26, 700, 701, 702, 703, 18276, 18277, 18278].each do |i|
print "#{i} -> "
puts a.position_to_column_notation i
end
[ 'A', 'Y', 'Z', 'AA', 'ZY', 'ZZ','AAA','AAB','ZZY','ZZZ','AAAA' ].each do |i|
print "#{i} -> "
puts a.column_notation_to_position i
end
__END__
$ ruby excel_spreedsheet_column_notation_calculator.rb
0 -> A
24 -> Y
25 -> Z
26 -> AA
700 -> ZY
701 -> ZZ
702 -> AAA
703 -> AAB
18276 -> AAZY
18277 -> AAZZ
18278 -> AAAA
A -> 0
Y -> 24
Z -> 25
AA -> 26
ZY -> 700
ZZ -> 701
AAA -> 702
AAB -> 703
ZZY -> 18276
ZZZ -> 18277
AAAA -> 18278
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment