分享一个 excel 处理中数字和字母相互转换的函数

def num_to_char(to_lower=None, to_capital=None):
"""
数字转字母,主要用于 excel 处理
:param to_lower: 转小写字母
:param to_capital: 转大写字母
:return:str
"""
if not to_lower and not to_capital:
return ''
else:
if to_lower:
init_num = to_lower
increment = ord(‘a’) - 1
else:
init_num = to_capital
increment = ord(‘A’) - 1
integer, remainder = divmod(init_num, 27)
char = chr(remainder + increment)
res_char = char * (integer + 1)
return res_char

if name == ‘main’:
print(num_to_char(1)) ==> a
print(num_to_char(2)) ==> b
print(num_to_char(26)) ==> z
print(num_to_char(‘‘, 1)) ==> A
print(num_to_char(’’, 2)) ==> B
print(num_to_char('', 26)) ==> Z