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

我想要将行和列索引转换为像“A1”这样的Excel字母数字单元格引用。 我正在使用python和openpyxl,我怀疑这个包里有一个实用程序,但是在search之后我还没find任何东西。

我写了下面这个,它可以工作,但是如果可用,我宁愿使用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) 

有谁知道更好的方法来做到这一点?

下面是使用@ Rick的答案openpyxl.utils.get_column_letter全新xlref

 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' 

老问题,但可能有帮助:使用XlsxWriter时 ,可以使用xl_rowcol_to_cell()

 from xlsxwriter.utility import xl_rowcol_to_cell cell = xl_rowcol_to_cell(1, 2) # C2 

请参阅使用单元格表示法 。

看起来像openpyxl.utils.get_column_letter与上面我的列函数做的function相同,毫无疑问比我更强硬一点。 谢谢阅读!