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