Get Excel-Style Column Names from Column Number

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

    I think it is something like this :

    def get_col(col):
        """Get excel-style column names"""
        (div, mod) = divmod(col, 26)
        if div == 0:
            return str(unichr(mod+64))
        elif mod == 0:
            return str(unichr(div+64-1)+'Z')
        else:
            return str(unichr(div+64)+unichr(mod+64))
    

    Some tests :

    >>> def get_col(col):
    ...     (div, mod) = divmod(col, 26)
    ...     if div == 0:
    ...         return str(unichr(mod+64))
    ...     elif mod == 0:
    ...         return str(unichr(div+64-1)+'Z')
    ...     else:
    ...         return str(unichr(div+64)+unichr(mod+64))
    ... 
    >>> get_col(105)
    'DA'
    >>> get_col(104)
    'CZ'
    >>> get_col(1)
    'A'
    >>> get_col(55)
    'BC'
    

提交回复
热议问题