python实现Excel的表头与索引之间的转换

字母转数字

def get_index(capital):
    """
    大写字母(Excel列头)转索引
    :param capital: 'A' --> 0, 'AA' --> 26
    :return: int
    """
    number = 0
    capital = capital.upper()
    for char in capital:
        number = number * 26 + ord(char) - ord('A') + 1
    return number - 1

数字转字母

def get_char(number):
    """
    索引转大写字母(Excel列头)
    :param number: 0 --> 'A', 26 --> 'AA'
    :return: str
    """
    factor, moder = divmod(number, 26)
    mod_char = chr(moder + 65)
    if factor:
        mod_char = get_char(factor - 1) + mod_char
    return mod_char
posted @ 2021-09-03 11:01  Rong_Z  阅读(320)  评论(0编辑  收藏  举报