在python/openpyx中将Excel行、列索引转换为字母数字单元格引用

2024-09-24 00:25:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将行和列索引转换为一个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)

有人知道更好的方法吗?


Tags: columnsstringreturndefa1columnrowc2