08-列字母和数字之间的转换
13.3.4 列字母和数字之间的转换
要从字母转换到数字,就调用 openpyxl.utils.column_index_from_string()
函数。要从数字转换到字母,就调用 openpyxl.utils.get_column_letter()
函数。在交互式环境中输入以下代码:
>>> import openpyxl
>>> from openpyxl.utils import get_column_letter, column_index_from_string
>>> get_column_letter(1) # Translate column 1 to a letter.
'A'
>>> get_column_letter(2)
'B'
>>> get_column_letter(27)
'AA'
>>> get_column_letter(900)
'AHP'
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb['Sheet1']
>>> get_column_letter(sheet.max_column)
'C'
>>> column_index_from_string('A') # Get A's number.
1
>>> column_index_from_string('AA')
27
在从 openpyxl.utils
模块引入这两个函数后,那就可以调用 get_column_letter()
了。传入像27这样的整数,弄清楚第27列的字母是什么。函数 column_index_from_string()
做的事情相反:传入一列的字母名称,它告诉你该列是第几列。要使用这些函数,不必加载一个工作簿。也可以加载一个工作簿,取得 Worksheet
对象,并使用 Worksheet
对象的属性,如 max_column
,来取得一个整数。然后,将该整数传递给 get_column_letter()
。