Skip to content

Instantly share code, notes, and snippets.

@blvz
Created January 6, 2013 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blvz/4466132 to your computer and use it in GitHub Desktop.
Save blvz/4466132 to your computer and use it in GitHub Desktop.
# 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.

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