我想将行和列索引转换为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)
有谁知道更好的方法吗?
解决方法:
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'
标签:openpyxl,python,excel
来源: https://codeday.me/bug/20190727/1557993.html