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

标签 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)

有谁知道更好的方法吗?

最佳答案

这是使用 openpyxl.utils.get_column_letter 的全新 xlref来自@Rick 的回答:

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)

现在

>>> xlref(0, 0)
'A1'
>>> xlref(100, 100)
'CW101'

关于python - 将 Excel 行、列索引转换为 python/openpyxl 中的字母数字单元格引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31420817/

相关文章:

python - 填充行时更改Excel文件中的行

python - Google App Engine 转换 API 因 BackendError 而失败

python - 如何处理列名和创建新列

python - 如何将一列中的文本拆分为多行

java - 使用 apache POI 在现有 Excel 文件之间插入新列

excel - 从 Excel 将工作表另存为 CSV

python - 在 Openpyxl 中跳过第一行

Python将数据框附加到现有的excel文件和工作表

python - 查找 XPath 段落(以下兄弟?)

database - 使用 Excel 作为 ODBC 数据库