环境
安装 openpyxl模块
pip install openpyxl
读取Excel文档
使用openpyxl打开excel文档
openpyxl.load_workbook() 函数接受文件名,返回一个workbook数据类型的值,这个workbook对象代表打开的excel文件。
>>> import openpyxl
>>> xls=openpyxl.load_workbook('E:\programmer\code\python\AutomateTheBoringStuff\selenium\AutoArrangementDocument\Source\告警IP列表Top20-1212.xlsx')
>>> type(xls)
<class 'openpyxl.workbook.workbook.Workbook'>
从工作簿中获取工作表
>>> import openpyxl
>>> wb=openpyxl.load_workbook('E:\programmer\code\python\AutomateTheBoringStuff\selenium\AutoArrangementDocument\Source\告警IP列表Top20-1212.xlsx')
#列举表名
>>> wb.get_sheet_names()
__main__:1: DeprecationWarning: Call to deprecated function get_sheet_names (Use wb.sheetnames).
['1211', 'Sheet1', 'Sheet2']
#传递表名字符串
>>> sheet=wb.get_sheet_by_name('1211')
__main__:1: DeprecationWarning: Call to deprecated function get_sheet_by_name (Use wb[sheetname]).
>>> sheet
<Worksheet "1211">
#表的类型
>>> type(sheet)
<class 'openpyxl.worksheet.worksheet.Worksheet'>
>>> sheet.title
'1211'
#取得工作簿中的活动表
>>> another_sheet=wb.get_active_sheet()
__main__:1: DeprecationWarning: Call to deprecated function get_active_sheet (Use the .active property).
>>> another_sheet
<Worksheet "Sheet1">
从表中取得单元格
>>> sheet['A1']
<Cell '1211'.A1>
>>> sheet['A1'].value
'序号'
>>> B=sheet['B1']
#使用名字访问Cell对象
>>> B
<Cell '1211'.B1>
#cell对象有一个value属性,cell对象还有row、column和cordinate属性,提供该单元格的位置信息
>>> B.value
'受影响IP'
执行语句报错
TypeError: can only concatenate str (not "int") to str
>>> 'Row'+str(B.row)+','+'Cloumn'+B.column+'is'+B.value
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
执行成功,coordinate=row+column
>>> 'Cell '+B.coordinate+' is '+B.value
'Cell B1 is 受影响IP'
调用cell方法,传入row和column的值
>>> sheet.cell(row=1,column=3)
<Cell '1211'.C1>
>>> sheet.cell(row=1,column=3).value
'告警次数'
打印奇数行的第二列的值
>>> for i in range(1,20,2):
... print(i,sheet.cell(row=i,column=2).value)
...
1 受影响IP
3 10.224.196.36
5 10.4.176.131
7 10.4.2.60
9 10.4.93.12
11 10.6.150.126
13 10.6.207.8
15 10.6.120.167
17 10.6.103.31
19 10.4.16.159
通过get_highest_row和get_highest_column方法,确定表的大小
报错,没有该方法,已经被删除。被max_row和max_columnt替代。
Worksheet' object has no attribute 'get_highest_row'
成功获取到了表的大小
>>> sheet.max_row
21
>>> sheet.max_column
8