前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python | 如何使用Python操作Excel(二)

Python | 如何使用Python操作Excel(二)

作者头像
LogicPanda
发布2019-07-30 14:58:07
5.9K0
发布2019-07-30 14:58:07
举报

0 前言

在阅读本文之前,请确保您已满足或可能满足一下条件:

  1. 请确保您具备基本的Python编程能力。
  2. 请确保您会使用Excel。
  3. 请确保您的电脑已经安装好Python且pip可用。
  4. 请确保您已经读过前文:

从如何使用Python操作Excel(一)中,我们可以得到一个“example.xlsx”文件,内容如图。

本文会继续讲解openpyxl的用法。

1. 在工作表中插入/删除行/列

对工作表的行或列进行操作时,使用Worksheet类中的方法,insert_row(),delete_row(),insert_col(),delete_col()

from openpyxl import load_workbook
import openpxl
wb = load_workbook("example.xlsx")
ws = wb.get_sheet_by_name("demo")
ws.insert_rows(1) # 在第一行前插入一行
ws.insert_rows(1, 2) # 在第一行前插入两个
ws.delete_rows(2) # 删除第二行
ws.delete_rows(2, 2) # 删除第二行及其后边一行(共两行)
ws.insert_cols(3) # 在第三列前插入一列
ws.insert_cols(3, 2) # 在第三列前插入两列
ws.delete_cols(4) # 删除第四列
ws.delete_cols(4, 2) #删除第四列及其后边一列(共两列)
wb.save("example.xlsx")

2. 访问单元格

在前文中我们讲到了如何访问单元格,如:

ws['A1']
ws['A1'].value

我们还可以使用行或列的方式访问:

ws['A'][1].value # ws['A1'].value
ws[1][2].value # ws['C1'].value
ws['A'] # 会返回元祖,‘A’列中所有的内容
ws[1] # 会返回元祖,第1行中所有的内容
>>> ws[1]      
(<Cell 'demo'.A1>, <Cell 'demo'.B1>, <Cell 'demo'.C1>, <Cell 'demo'.D1>, <Cell 'demo'.E1>, <Cell 'demo'.F1>, <Cell 'demo'.G1>, <Cell 'demo'.H1>, <Cell 'demo'.I1>, <Cell 'demo'.J1>, <Cell 'demo'.K1>, <Cell 'demo'.L1>, <Cell 'demo'.M1>, <Cell 'demo'.N1>, <Cell 'demo'.O1>, <Cell 'demo'.P1>, <Cell 'demo'.Q1>, <Cell 'demo'.R1>, <Cell 'demo'.S1>)
>>> ws['A']      
(<Cell 'demo'.A1>, <Cell 'demo'.A2>, <Cell 'demo'.A3>, <Cell 'demo'.A4>, <Cell 'demo'.A5>, <Cell 'demo'.A6>, <Cell 'demo'.A7>, <Cell 'demo'.A8>, <Cell 'demo'.A9>, <Cell 'demo'.A10>, <Cell 'demo'.A11>, <Cell 'demo'.A12>, <Cell 'demo'.A13>, <Cell 'demo'.A14>, <Cell 'demo'.A15>, <Cell 'demo'.A16>, <Cell 'demo'.A17>, <Cell 'demo'.A18>, <Cell 'demo'.A19>)

PS:我们还可用切片的方式来访问一个范围内的单元格。

>>> ws["A1:B3"]  
(
(<Cell 'demo'.A1>, <Cell 'demo'.B1>),
(<Cell 'demo'.A2>, <Cell 'demo'.B2>),
(<Cell 'demo'.A3>, <Cell 'demo'.B3>)
)
>>> ws["A1:B3"][1][1].value      
4
>>> ws['A1':'B3']    
(
(<Cell 'demo'.A1>, <Cell 'demo'.B1>),
(<Cell 'demo'.A2>, <Cell 'demo'.B2>),
(<Cell 'demo'.A3>, <Cell 'demo'.B3>)
)
>>>

请留意两种切片的不同。

还可以使用行切片或者列切片:

>>> ws['A:B']
((<Cell 'Sheet'.A1>, <Cell 'Sheet'.A2>, <Cell 'Sheet'.A3>, <Cell 'Sheet'.A4>, <Cell 'Sheet'.A5>, <Cell 'Sheet'.A6>, <Cell 'Sheet'.A7>, <Cell 'Sheet'.A8>, <Cell 'Sheet'.A9>, <Cell 'Sheet'.A10>, <Cell 'Sheet'.A11>, <Cell 'Sheet'.A12>, <Cell 'Sheet'.A13>, <Cell 'Sheet'.A14>, <Cell 'Sheet'.A15>, <Cell 'Sheet'.A16>, <Cell 'Sheet'.A17>, <Cell 'Sheet'.A18>, <Cell 'Sheet'.A19>), (<Cell 'Sheet'.B1>, <Cell 'Sheet'.B2>, <Cell 'Sheet'.B3>, <Cell 'Sheet'.B4>, <Cell 'Sheet'.B5>, <Cell 'Sheet'.B6>, <Cell 'Sheet'.B7>, <Cell 'Sheet'.B8>, <Cell 'Sheet'.B9>, <Cell 'Sheet'.B10>, <Cell 'Sheet'.B11>, <Cell 'Sheet'.B12>, <Cell 'Sheet'.B13>, <Cell 'Sheet'.B14>, <Cell 'Sheet'.B15>, <Cell 'Sheet'.B16>, <Cell 'Sheet'.B17>, <Cell 'Sheet'.B18>, <Cell 'Sheet'.B19>))
>>> ws[1:2]
((<Cell 'Sheet'.A1>, <Cell 'Sheet'.B1>, <Cell 'Sheet'.C1>, <Cell 'Sheet'.D1>, <Cell 'Sheet'.E1>, <Cell 'Sheet'.F1>, <Cell 'Sheet'.G1>, <Cell 'Sheet'.H1>, <Cell 'Sheet'.I1>, <Cell 'Sheet'.J1>, <Cell 'Sheet'.K1>, <Cell 'Sheet'.L1>, <Cell 'Sheet'.M1>, <Cell 'Sheet'.N1>, <Cell 'Sheet'.O1>, <Cell 'Sheet'.P1>, <Cell 'Sheet'.Q1>, <Cell 'Sheet'.R1>, <Cell 'Sheet'.S1>), (<Cell 'Sheet'.A2>, <Cell 'Sheet'.B2>, <Cell 'Sheet'.C2>, <Cell 'Sheet'.D2>, <Cell 'Sheet'.E2>, <Cell 'Sheet'.F2>, <Cell 'Sheet'.G2>, <Cell 'Sheet'.H2>, <Cell 'Sheet'.I2>, <Cell 'Sheet'.J2>, <Cell 'Sheet'.K2>, <Cell 'Sheet'.L2>, <Cell 'Sheet'.M2>, <Cell 'Sheet'.N2>, <Cell 'Sheet'.O2>, <Cell 'Sheet'.P2>, <Cell 'Sheet'.Q2>, <Cell 'Sheet'.R2>, <Cell 'Sheet'.S2>))

3. 使用公式

首先你要清晰的明白,你要使用的公式是什么。同时你需要知道的是,openpyxl能够在工作表中执行公式进行计算,但是并不能在程序中打印公式的值

>>> ws['A20']="=SUM(A1:A19)"      
>>> ws['A20'].value
'=SUM(A1:A19)'
>>> wb.save("formula.xlsx") # 请查看A20

即便如此,openpyxl却可以帮助你检查公式名是否正确:

>>> from openpyxl.utils import FORMULAE
>>> "SUM" in FORMULAE      
True

当然,你也可以用print(FORMULAE) 来看看都有什么公式可以用(与Excel并没有什么不一样)。

4. 移动单元格

使用ws.move_range()方法来移动单元格。

ws.move_range("D4:F10", rows=-1, cols=2)

会将单元格D4-F10,向上移动1行,想右移动两行。参数ows和cols用来控制单元格的移动方向。如果目标单元格有内容,会被覆盖。

5. 拆分/合并单元格

使用ws.merge_cells()和ws.unmerge_cell()l来和合并,拆分单元格。

>>> ws.merge_cells('A2:D2') # 值为ws['A2']的值
>>> ws["A2"] # <Cell 'demo'.A2>
>>> ws["A2"].value # 2
>>> ws["B2"].value # 空
>>> ws.unmerge_cells('A2:D2') # 值会回到ws['A2'],'B2:D2'会为空。
>>> ws.merge_cells(start_row=2, start_column=1, end_row=4, end_column=4)
>>> ws.unmerge_cells(start_row=2, start_column=1, end_row=4, end_column=4)

6. 插入图片

想要用openpyxl向工作表中插入图片,需要安装Pillow库:

from openpyxl.drawing.image import Image
img = Image('logo.jpg')      
ws.add_image(img, 'A21')
wb.save("img.xlsx")

7. 折叠

ws1 = wb.create_sheet() # 新建一张表Sheet
ws1.column_dimensions.group('A','D', hidden=True) # 列折叠,A-D列
ws1.row_dimensions.group(1,10, hidden=True) # 行折叠 1-10行
wb.save('group.xlsx')

8. 只读模式与只写模式

只读模式,仅用来读取文档内信息,不可写。

wb = load_workbook(filename="example.xlsx", read_only=True)
wb.create_sheet("test.xlsx") # 会报错
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    wb.create_sheet("test.xlsx")
  File "D:\Python\lib\site-packages\openpyxl\workbook\workbook.py", line 194, in create_sheet
    raise ReadOnlyWorkbookException('Cannot create new sheet in a read-only workbook')
openpyxl.utils.exceptions.ReadOnlyWorkbookException: Cannot create new sheet in a read-only workbook

只写模式,仅用来写入数据。

wb = Workbook(write_only=True)
ws = wb.create_sheet()
type(ws) # <class 'openpyxl.worksheet._write_only.WriteOnlyWorksheet'>
hasattr(ws,"value") # false
hasattr(ws,"title") # True

即是说,ws已经不是worksheet对象,而是WriteOnlyWorksheet对象,也没有value属性,不可以读取单元格的值。这样做是为了让Python处理只有写入大量数据的情况,更快。

9.数字格式

可以使用Cell对象的nember_format属性来查看单元格的数字样式。

wb = load_workbook("example.xlsx")
ws = wb.active
ws['A1'].nember_format # 'General'
# 现在将单元格的数字格式设置为数值
ws['A1'].nember_format # '0.00_ '
# 可以在Python中修改数字格式如:
ws['A1'].nember_format = 'General'
# 单元格可以直接赋值时间日期类型的数据类型,如:
ws['A1'] = datetime.datetime.now()
ws['A1'].value # datetime.datetime(2019, 6, 9, 19, 57, 40, 918556)
# 可以用is_date属性判断单元格是否为日期类型的数据
ws['A1'].is_date

10. 复习下今天内容

今天的内容主要是及第一篇文章之后,继续讲如何使用Python操作单元格和工作表。

  1. 插入/删除行或列,访问单元格的方法
  2. 移动单元格,合并/拆分单元格
  3. 插入图像、使用公式折叠行/列
  4. 使用数字格式,只读和只写模式

好了,今天的内容就到这里了。我们下次见。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-06-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 编程杂艺 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 0 前言
  • 1. 在工作表中插入/删除行/列
  • 2. 访问单元格
  • 3. 使用公式
  • 4. 移动单元格
  • 5. 拆分/合并单元格
  • 6. 插入图片
  • 7. 折叠
  • 8. 只读模式与只写模式
  • 9.数字格式
  • 10. 复习下今天内容
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档