python处理Excel电子表格

环境

安装 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_rowget_highest_column方法,确定表的大小

报错,没有该方法,已经被删除。被max_row和max_columnt替代

Worksheet' object has no attribute 'get_highest_row'

成功获取到了表的大小

>>> sheet.max_row
21
>>> sheet.max_column
8
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值