Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 304
Rick Avatar asked Jul 15 '15 03:07

Rick


People also ask

How do I find my cell number for Openpyxl?

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.


2 Answers

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'
like image 117
Michael Currie Avatar answered Sep 20 '22 11:09

Michael Currie


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!

like image 26
Rick Avatar answered Sep 24 '22 11:09

Rick