I\'m trying to covert a coordinate value in excel to a row number and column number in openpyxl.
For example if my cell coordinate is D4 I want to find the correspon
Old topic, but the answer is not correct!
dylnmc method was a good one, but has some errors. The calculated row for cell coords like "AA1" or "AAB1" is not correct.
Below is the corrected version as a function.
NOTE: This function returns the real coordinated. If you want to use it for example in ExcelWriter, both ROW and COL should be deducted by one. So replace the last line with return(row-1,col-1)
For example 'AA1' is [1,27] and 'AAA1' is [1,703]; but the python must have them as [0,26] and [0,702].
import re
def coord2num(coord):
cell = coord.lower()
# generate matched object via regex (groups grouped by parentheses)
m = re.match('([a-z]+)([0-9]+)', cell)
if m is None:
print('Invalid cell: {}'.format(cell))
return [None,None]
else:
col = 0
for i,ch in enumerate(m.group(1)[::-1]):
n = ord(ch)-96
col+=(26**i)*(n)
row = int(m.group(2))
return[row,col]