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