将Excel行,列索引转换为python / openpyxl中的字母数字单元格引用

Ric*_*ick 3 python excel openpyxl

我想将行索引和列索引转换为Excel字母数字单元格引用,例如“ A1”。我正在使用python和openpyxl,我怀疑该程序包中的某个地方可以执行此操作,但是经过一些搜索后我什么都没找到。

我写了下面的代码,它可以工作,但是我宁愿使用openpyxl软件包中的一部分(如果有的话)。

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)
Run Code Online (Sandbox Code Playgroud)

有人知道更好的方法吗?

Mic*_*rie 5

下面是完整的新的xlref使用openpyxl.utils.get_column_letter从@里克的回答:

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)
Run Code Online (Sandbox Code Playgroud)

现在

>>> xlref(0, 0)
'A1'
>>> xlref(100, 100)
'CW101'
Run Code Online (Sandbox Code Playgroud)


Ric*_*ick 2

看起来openpyxl.utils.get_column_letter 的功能与我上面的 columns 功能相同,并且毫无疑问比我的更坚固一些。谢谢阅读!