Created
February 25, 2014 03:40
-
-
Save carymrobbins/9202238 to your computer and use it in GitHub Desktop.
Convert an Excel cell address to a tuple of (row, col)
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
| import re | |
| def excel_tuple(address): | |
| """ | |
| Takes an Excel address and converts it to a tuple. Used as a helper for | |
| looking up (row, column) to pass into sheet.cell(row, col). | |
| >>> assert excel_tuple('A1') == (0, 0) | |
| >>> assert excel_tuple('Z10') == (9, 25) | |
| >>> assert excel_tuple('AAA999') == (998, 702) | |
| :type address: basestring | |
| :rtype: (int, int) | |
| """ | |
| address = address.upper() | |
| m = _excel_tuple_regex.match(address) | |
| if not m or not m.group('col') or not m.group('row'): | |
| raise ValueError('Invalid Excel address {!r}'.format(address)) | |
| col = -1 | |
| seed = 0 | |
| for c in reversed(m.group('col')): | |
| col += ord(c) - ord('A') + 26 ** seed | |
| seed += 1 | |
| row = int(m.group('row')) - 1 | |
| return row, col | |
| _excel_tuple_regex = re.compile(r'^(?P<col>[A-Z]+)(?P<row>\d+)$') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment