Last active
August 12, 2018 02:54
-
-
Save adamabernathy/40c24e8df2062ffdf76c3cecb7ece7f4 to your computer and use it in GitHub Desktop.
Convert Excel columns to index and back
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
| # 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