Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
module ExcelColumnsConverions
# convert the column name ("A", "ACB", ...) to an number (1-based)
def excel_col_number(str)
offset = 'A'.ord - 1
str.chars.inject(0){ |x,c| x*26 + c.ord - offset }.to_i
end
# convert the column number to a string ("A", "ACB", ...)
def excel_col_string(number)
# limit: 16.384
raise "Number must be less than or equal to 16384" if number>16384
n = number-1
d3 = (n-26*27)/(26*26)
d3 = d3<0 ? -1 : d3
d2 = (n-26)/26
d2 = d2<0 ? -1 : d2%26
d1 = n%26
arr = ("A".."Z").to_a
arr_w_space = [""]+arr
[arr_w_space[d3+1], arr_w_space[d2+1], arr[d1]].join
end
def check(max)
1.upto(max) do |n|
s = excel_col_string(n)
nn = excel_col_index(s)
puts "#{n} -> '#{s}' -> #{nn}" if n!=nn
end
end
end
@iwan

This comment has been minimized.

Copy link
Owner Author

iwan commented May 25, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.