Python 转数字为Excel列,转列为数字

def convent_column_to_char(column):
	"""
	将数字转换为Excel列
	1 => A, 2 => B, ......, 27 => AA
	:param column: int
	:return: str
	"""
	if not isinstance(column, int):
		return column
	tStr = str()
	while column != 0:
		res = column % 26
		if res == 0:
			res = 26
			column -= 26
		tStr = chr(ord('A') + res - 1) + tStr
		column = column // 26
	return tStr


def colname_to_num(colname):
	if not isinstance(colname, 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


if __name__ == "__main__":
    l = list()
    n = list()
    for a in range(1, 1001):
        l.append(convent_column_to_char(a))
    print(l)
    for a in l:
        n.append(colname_to_num(a))
    print(n)

There are no comment yet.

HTML tag cannot be used in this comment.