Created
May 25, 2018 07:09
-
-
Save iwan/72b56eff359e93e323bbf3a9ebc40d3a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
excel_col_number
function copied from https://stackoverflow.com/questions/26771129/convert-excel-column-letter-to-integer-in-ruby