Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# 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
@blvz
Copy link
Author

blvz commented Jan 6, 2013

I'm using it with Roo and ExcelCompare in a project.

Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment