Skip to content

Instantly share code, notes, and snippets.

@adamabernathy
Last active August 12, 2018 02:54
Show Gist options
  • Select an option

  • Save adamabernathy/40c24e8df2062ffdf76c3cecb7ece7f4 to your computer and use it in GitHub Desktop.

Select an option

Save adamabernathy/40c24e8df2062ffdf76c3cecb7ece7f4 to your computer and use it in GitHub Desktop.
Convert Excel columns to index and back
# coding: utf-8
'''Excel Column Conversion, (C) 2018 Adam C. Abernathy, Lic. MIT'''
def excel_alpha_to_index(column_name, alphabet='abcdefghijklmnopqrstuvwxyz'):
return sum([(alphabet.find(column_name[-i - 1].lower()) + 1) * pow(len(alphabet), i)
for i in reversed(xrange(len(column_name)))])
def excel_index_to_alpha(postion, alphabet='abcdefghijklmnopqrstuvwxyz'):
column_name = ''
while postion > 0:
mod = (postion - 1) % len(alphabet)
column_name = alphabet[mod] + column_name
postion = (postion - mod) / len(alphabet)
return column_name.upper()
if __name__ == '__main__':
# -- Tests --
# to index, base 26, normal alphabet
print excel_alpha_to_index('CDA') == 2133
print excel_alpha_to_index('A') == 1
print excel_alpha_to_index('c') == 3
print excel_alpha_to_index('AA') == 27
print excel_alpha_to_index('AB') == 28
# to index, base 5
alphabet = 'abcde'
print excel_alpha_to_index('CDA', alphabet) == 96
print excel_alpha_to_index('A', alphabet) == 1
print excel_alpha_to_index('c', alphabet) == 3
print excel_alpha_to_index('AA', alphabet) == 6
print excel_alpha_to_index('AB', alphabet) == 7
# to alpha
print excel_index_to_alpha(27) == 'AA'
print excel_index_to_alpha(2133) == 'CDA'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment