Get Excel-Style Column Names from Column Number

前端 未结 8 1570
慢半拍i
慢半拍i 2020-12-01 12:38

This is the code for providing the COLUMN name when the row and col ID is provided but when I give values like row = 1 and col = 104, it should return CZ<

8条回答
  •  一整个雨季
    2020-12-01 13:23

    You have a couple of index issues:

    So to fix your problem, you need to make all your indices match:

    def colToExcel(col): # col is 1 based
        excelCol = str()
        div = col 
        while div:
            (div, mod) = divmod(div-1, 26) # will return (x, 0 .. 25)
            excelCol = chr(mod + 65) + excelCol
    
        return excelCol
    
    print colToExcel(1) # => A
    print colToExcel(26) # => Z
    print colToExcel(27) # => AA
    print colToExcel(104) # => CZ
    print colToExcel(26**3+26**2+26) # => ZZZ
    

提交回复
热议问题