Get Excel-Style Column Names from Column Number

前端 未结 8 1577
慢半拍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:21

    def ColNum2ColName(n):
       convertString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
       base = 26
       i = n - 1
    
       if i < base:
          return convertString[i]
       else:
          return ColNum2ColName(i//base) + convertString[i%base]
    

    EDIT: Right, right zondo.

    I just approached A, B, .. AA, AB, ... as a numeric base with digits A-Z.

    A = 1
    B = 2
     .
     .
    X = 24
    Y = 25
    Z = 26
     .
     .
     .
    

    It's an easy way without any while loop etc. and works for any number > 0.

提交回复
热议问题