Python 3 實現數字轉換成Excel列名(10進位制到26進位制的轉換函式)
阿新 • • 發佈:2018-11-11
背景:
最近在看一些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]