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?
The values that are stored in the cells of an Excel Sheet can be accessed easily using the openpyxl library. To read the cell values, we can use two methods, firstly the value can be accessed by its cell name, and secondly, we can access it by using the cell() function.
Here's the full new xlref
using openpyxl.utils.get_column_letter
from @Rick's answer:
from openpyxl.utils import get_column_letter
def xlref(row, column, zero_indexed=True):
if zero_indexed:
row += 1
column += 1
return get_column_letter(column) + str(row)
Now
>>> xlref(0, 0)
'A1'
>>> xlref(100, 100)
'CW101'
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With