点击上方“Python爬虫与数据挖掘”,进行关注
回复“书籍”即可获赠Python从入门到进阶共10本电子书
今
日
鸡
汤
岐王宅里寻常见,崔九堂前几度闻。
前言
当你需要每天对 Excel
做大量重复的操作,如果只靠人工来做既浪费时间,又十分枯燥,好在 Python
为我们提供了许多操作 Excel
的模块,能够让我们从繁琐的工作中腾出双手。
今天就和大家分享一个快速处理 Excel
的模块 openpyxl
,它的功能相对与其他模块更为齐全,足够应对日常出现的问题。
openpyxl 安装
直接在命令提示符中输入。
pip install openpyxl
或使用豆瓣镜像安装。
pip install -i https://pypi.douban.com/simple openpyxl
安装成功后,下面就看看如何使用
打开/创建工作簿
「示例工作簿」工作表【一等奖】
工作表【二等奖】
(1)打开本地工作簿
>>> from openpyxl import load_workbook
>>> wb = load_workbook('获奖名单.xlsx')
(2)创建空的工作薄
>>> from openpyxl import Workbook
>>> wb1 = Workbook()
访问工作表
创建新工作表,可指定插入的位置(0:首位,-1:末尾
)。
>>> wb.create_sheet('new_sheet', 0)
<Worksheet "new_sheet">
获取工作簿中所有工作表。
>>> wb.sheetnames
['new_sheet', '一等奖', '二等奖']
使用列表推导式遍历获取所有工作表名称。
>>> [sheet.title for sheet in wb]
['new_sheet', '一等奖', '二等奖']
使用 wb[sheetname]
来获取一个工作表对象
>>> wb['二等奖']
<Worksheet "二等奖">
获取活动表(即打开工作簿首先出现的工作表)。
>>> wb.active
<Worksheet "一等奖">
获取工作表行列信息。
>>> sheet1 = wb['一等奖']
>>> sheet1.max_column
7
>>> sheet1.max_row
6
获取单元格信息
访问某个单元格
>>> sheet1['D3']
<Cell '一等奖'.D3>
>>> sheet1.cell(row=3, column=4)
<Cell '一等奖'.D3>
如果访问单元格式添加 value
参数则会修改当前单元格的值。
>>> sheet1.cell(3, 4).value
'基于Spark、Python的医护人员信息抽取与管理'
>>> sheet1.cell(3, 4, value='Python')
<Cell '一等奖'.D3>
>>> sheet1.cell(3, 4).value
'Python'
获取单元格的值、坐标、行索引、列索引。
>>> sheet1['D3'].value
'Python'
>>> sheet1['D3'].coordinate
'D3'
>>> sheet1['D3'].row
3
>>> sheet1['D3'].column
4
访问多个单元格
使用切片来访问多个单元格,这里的切片与列表切片有区别,列表切片是「前闭后开」,Excel 中的切片是「前闭后闭」。
(1)选取 A1:B2
区域的单元格。
>>> sheet1['A1':'B2']
((<Cell '一等奖'.A1>,
<Cell '一等奖'.B1>),
(<Cell '一等奖'.A2>,
<Cell '一等奖'.B2>))
选取单列数据。
>>> sheet1['D']
(<Cell '一等奖'.D1>,
...
<Cell '一等奖'.D6>)
选取B,C列数据。
>>> sheet1['B:C']
((<Cell '一等奖'.B1>,
...
<Cell '一等奖'.B6>),
(<Cell '一等奖'.C1>,
...
<Cell '一等奖'.C6>))
选取单行数据。
>>> sheet1[3]
(<Cell '一等奖'.A3>,
<Cell '一等奖'.B3>,
...
<Cell '一等奖'.F3>,
<Cell '一等奖'.G3>)
选取第2,3行数据。
>>> sheet1[2:3]
((<Cell '一等奖'.A2>,
...
<Cell '一等奖'.G2>),
(<Cell '一等奖'.A3>,
...
<Cell '一等奖'.G3>))
遍历获取数据
按行遍历指定范围(B2:C3
)数据。
>>> for row in sheet1.iter_rows(min_row=2, max_row=3, min_col=2, max_col=3):
for cell in row:
print(cell.coordinate)
B2
C2
B3
C3
按列遍历指定范围(B2:C3
)数据。
>>> for col in sheet1.iter_cols(min_row=2, max_row=3, min_col=2, max_col=3):
for cell in col:
print(cell.coordinate)
B2
B3
C2
C3
如果 iter_rows()/iter_cols()
中指定参数 values_only=True
,那么将只返回单元格的值
按行遍历所有数据。
>>> tuple(sheet1.rows)
((<Cell '一等奖'.A1>,
...
<Cell '一等奖'.G1>),
...
...
(<Cell '一等奖'.A6>,
...
<Cell '一等奖'.G6>))
按列遍历所有数据。
>>> tuple(sheet1.columns)
((<Cell '一等奖'.A1>,
...
<Cell '一等奖'.A6>),
...
...
(<Cell '一等奖'.G1>,
...
<Cell '一等奖'.G6>))
修改工作表
单元格赋值
新增一列计算 作者
人数。
>>> for row_index in range(2, sheet1.max_row + 1):
sheet1.cell(row_index, 8).value = len(sheet1.cell(row_index, 6).value.split(','))
![da8c0003fbbc2747047ae27bbf67ebe4.png](https://img-blog.csdnimg.cn/img_convert/da8c0003fbbc2747047ae27bbf67ebe4.png)
使用公式给单元格赋值,H7
统计作者总人数。
>>> sheet1['H7'] = '=SUM(H1:H6)'
![f9a38b1ed277c8e4f31cf8d89840e585.png](https://img-blog.csdnimg.cn/img_convert/f9a38b1ed277c8e4f31cf8d89840e585.png)
追加一行数据
使用列表按序传入值。
>>> sheet1.append([str(n) for n in range(6)])
使用字典指定
列索引:列值
。
>>> sheet1.append({'A':'1','C':'3'})
![f0eefbb04431b1e74060d66e688e5b0c.png](https://img-blog.csdnimg.cn/img_convert/f0eefbb04431b1e74060d66e688e5b0c.png)
插入空白行
在指定位置插入空白行, idx
行索引,插入的位置;amount
插入空白行的数量
>>> sheet1.insert_rows(idx=2, amount=2)
![cc1d87394014909048222f68c8b3e835.png](https://img-blog.csdnimg.cn/img_convert/cc1d87394014909048222f68c8b3e835.png)
删除工作表
>>> wb.remove(wb['new_sheet'])
保存工作簿
>>> wb.save('获奖名单V1.xlsx')
修改样式
字体
设置 B2
单元格字体格式为,颜色可以用十六进制颜色代码。
>>> from openpyxl.styles import Font
>>> new_font = Font(name='微软雅黑', size=20, color='3333CC', bold=True)
>>> sheet1['B2'].font = new_font
![82486eee59cc2b410b48a4b8cbf10a56.png](https://img-blog.csdnimg.cn/img_convert/82486eee59cc2b410b48a4b8cbf10a56.png)
单元格背景颜色
>>> from openpyxl.styles import PatternFill, colors
>>> sheet1["A2"].fill = PatternFill("solid", fgColor=colors.BLUE)
>>> sheet1["A3"].fill = PatternFill("solid", fgColor='FF66CC')
![d2a36ea8119a5f2603464001e3f57c57.png](https://img-blog.csdnimg.cn/img_convert/d2a36ea8119a5f2603464001e3f57c57.png)
对齐方式
设置 D2
中的数据 垂直居中
和 水平居中
。
>>> from openpyxl.styles import Alignment
>>> sheet1['D2'].alignment = Alignment(horizontal='center', vertical='center')
![a39ba70979762a13679f53a1dec26a62.png](https://img-blog.csdnimg.cn/img_convert/a39ba70979762a13679f53a1dec26a62.png)
行高/列宽
设置第2行行高为40,C列列宽为20。
>>> sheet1.row_dimensions[2].height = 40
>>> sheet1.column_dimensions['C'].width = 20
![84be9efaa5ae094aff0eeeb450ece3f1.png](https://img-blog.csdnimg.cn/img_convert/84be9efaa5ae094aff0eeeb450ece3f1.png)
合并/拆分单元格
合并单元格只需要指定左上角和右下角的单元格坐标。
>>> sheet.merge_cells('A1:C3')
![c6a98aec074da1166ec1812454d8854a.png](https://img-blog.csdnimg.cn/img_convert/c6a98aec074da1166ec1812454d8854a.png)
拆分单元格后,合并区域的值会赋给左上角单元格A1。
>>> sheet.unmerge_cells('A1:C3')
![7732b774e5a0f142549d799e744debf9.png](https://img-blog.csdnimg.cn/img_convert/7732b774e5a0f142549d799e744debf9.png)
欢迎大家积极尝试,有好的内容也可以分享给我噢!
![b5e9dea54579ac82d7d64f92503efb49.png](https://img-blog.csdnimg.cn/img_convert/b5e9dea54579ac82d7d64f92503efb49.png)
小伙伴们,快快用实践一下吧!如果在学习过程中,有遇到任何问题,欢迎加我好友,我拉你进Python学习交流群共同探讨学习。
------------------- End -------------------
往期精彩文章推荐:
欢迎大家点赞,留言,转发,转载,感谢大家的相伴与支持
想加入Python学习群请在后台回复【入群】
万水千山总是情,点个【在看】行不行
/今日留言主题/
随便说一两句吧~~