Rick Rick - 1 year ago 74
Python Question

Convert Excel row,column indices to alphanumeric cell reference in python/openpyxl

I want to convert the row and column indices into an Excel alphanumeric cell reference like 'A1'. I'm using python and openpyxl, and I suspect there's a utility somewhere in that package that does this, but I haven't found anything after some searching.

I wrote the following, which works, but I'd rather use something that's part of the openpyxl package if it's available.

def xlref(row,column):
"""
xlref - Simple conversion of row, column to an excel string format

>>> xlref(0,0)
'A1'
>>> xlref(0,26)
'AA1'
"""
def columns(column):
from string import uppercase
if column > 26**3:
raise Exception("xlref only supports columns < 26^3")
c2chars = [''] + list(uppercase)
c2,c1 = divmod(column,26)
c3,c2 = divmod(c2,26)
return "%s%s%s" % (c2chars[c3],c2chars[c2],uppercase[c1])
return "%s%d" % (columns(column),row+1)


Does anyone know a better way to do this?

Answer Source

Looks like openpyxl.utils.get_column_letter does the same function as my columns function above, and is no doubt a little more hardened than mine is. Thanks for reading!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download