字母转数字方法:
import re col = row = [] # 输入正确格式的定位,A2,AA2有效,AAB2无效 while len(col) == 0 or len(row) == 0 or len(col) > 1 or len(row) > 1: colrow = input(‘请输入单元格位置(例如B3,AAB3,a2,aaB4):‘) col = re.findall(‘([A-Za-z]+)\w+‘,colrow) row = re.findall(‘\w+(\d+)‘,colrow) if len(col[0]) > 2: col = [] #只接受两位字母的列标,超过2位的无效,A,AB有效,AAB无效 row = int(row[0]) #行标 col = col[0] # 输入为A2类型 if len(col) == 1: col = ord(col.upper())-ord(‘A‘) + 1 # 输入为AA2类型 elif len(col) == 2: col_1 = ord(col[0].upper())-ord(‘A‘) + 1 col_2 = ord(col[1].upper())-ord(‘A‘) + 1 col = col_1*26 + col_2 # 获取行列数 print(‘Column:‘,col,‘/ Row: ‘,row)
数字转字母方法:
import string letter = string.ascii_uppercase def num_to_letter(col,row): row = str(row+1) if col < 26: index = col + ord(‘A‘) return chr(index)+row else: col_1 = (col // 26) - 1 col_2 = (col % 26) return letter[col_1]+letter[col_2]+row print(num_to_letter(4,4))