Python 3 实现数字转换成Excel列名(10进制到26进制的转换函数)


背景:

  最近在看一些Python爬虫的相关知识,讲爬取的一些数据写入到Excel表中,当时当列的数目不确定的情况下,如何通过遍历的方式讲爬取的数据写入到Excel中。

开发环境: Python 3   openpyxl 

解决方案:Excel列名其实就是一个26进制的数,我们只需要实现26进制和10进制之间的转换就行列

代码:

 

def colname_to_num(colname):
    if type(colname) is not str:
        return colname


    col = 0
    power = 1


    for i in range(len(colname)-1,-1,-1):
        ch = colname[i]

        col += (ord(ch)-ord('A')+1)*power

        power *= 26

    return col



def column_to_name(colnum):
    if type(colnum) is not int:
        return colnum

    str = ''

    while(not(colnum//26 == 0 and colnum % 26 == 0)):

        temp = 25

        if(colnum % 26 == 0):
            str += chr(temp+65)
        else:
            str += chr(colnum % 26 - 1 + 65)

        colnum //= 26
        #print(str)
    #倒序输出拼写的字符串
    return str[::-1]

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM