Created
January 6, 2013 08:54
-
-
Save blvz/4466132 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
# converting back and forth between (excel) spreadsheets column name / alpha and column number / index | |
# by Rafael Belvederese, inpired by this thread: | |
# http://stackoverflow.com/questions/22708/how-do-i-find-the-excel-column-name-that-corresponds-to-a-given-integer | |
def alpha_to_index(alpha) | |
alpha.upcase! | |
if alpha.length == 1 | |
return alpha.bytes.to_a[0] - 65 | |
elsif alpha.length != 0 | |
return ((alpha_to_index(alpha[0]) + 1) * (26 ** (alpha.length - 1))) + alpha_to_index(alpha[1..-1]) | |
else | |
return nil | |
end | |
end | |
def index_to_alpha(index) | |
q = (index) / 26 | |
if q > 0 | |
index_to_alpha(q - 1) + ((index % 26) + 65).chr | |
else | |
(index + 65).chr | |
end | |
end | |
index = alpha_to_index('ach') | |
puts index # 761 | |
alpha = index_to_alpha(index) | |
puts alpha # ACH |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm using it with Roo and ExcelCompare in a project.