Python学习笔记:Excel相关之openpyxl

分步骤进行学习:
① 对 openpyxl 的 Tutorial 进行翻译理解
② 在初步掌握整个运行逻辑及功能后尝试小工具制作
③ 最终进行总结

源地址:https://openpyxl.readthedocs.io/en/stable/tutorial.html#create-a-workbook

Tutorial Part

01 创建工作簿(Create a workbook)

There is no need to create a file on the filesystem to get started with openpyxl. Just import the Workbook class and start work.
使用openpyxl时无需先在系统中创建一个实体文件。只需要调用Workbook这个Class即可。

# 从 openpyxl 中调用 Workbook
# 使用 Workbook() 新建一个excel工作簿,同时将这个工作簿赋值给 wb

from openpyxl import Workbook
wb = Workbook()
  • 在 openpyxl 中并不需要现在系统中创建一个 excel 文件,也就是说就如同直接使用 MS Excel 新建文件一样,会新建一个“未保存”的临时文件供使用。

A workbook is always created with at least one worksheet. You can get it by using the Workbook.active property
一个工作簿创建时至少存在一个工作表,它可以通过 Workbook.active 来被调用。

sht = wb.active   # 不少文章中都是用 ws 来代替 worksheet 的,不过我还是比较习惯 sht 的写法呐
  • 一个工作簿创建时至少会带有一个工作表——这点感觉是使用除去VB以外控制excel的通用情况,实际上新建的工作簿应该会有3个sheet(直接使用MS Office Excel创建的话)。
  • 新鲜出炉的工作簿,可以通过 Workbook.active 这个属性来获取这张工作表。

>>> 小语の胡思乱想
在VB中其实也有类似的写法,不过可能会更加直观一些。
例如正在使用的工作簿、工作表直接会被标记成 Activeworkbook, Activeworksheet,然后赋值的话需要将这些object运用Set来确定赋值关系。在Python中似乎只需要将这些object像value一样赋值给变量就可以了——所以其实很好奇,是不是python中的变量可以是任何内容?甚至说,其实并不是赋值,而是一种链接关系呢?

—— Note ——
This is set to 0 by default. Unless you modify its value, you will always get the first worksheet by using this method.
这个 wb.active 会被默认放在0号位置(第一张表)。除非你重新定义他的值,否则你始终可以通过这个方法来调取第一张表。

You can create new worksheets using the Workbook.create_sheet() method.
*你可以通过 Workbook.create_sheet() 方法来新建工作表。

TempSht = wb.create_sheet("MySheet",0)
# 在0号位置创建一张表格(相当于在最前面插入一张新表),并取名为 MySheet
# 若 wb.create_sheet("MySheet") 则新建并插入到最后

Sheets are given a name automatically when they are created. They are numbered in sequence (Sheet, Sheet1, Sheet2, …). You can change this name at any time with the Worksheet.title property
工作表在创建时会自动生成一个名称。他们通常按照数字进行编号(如Sheet,Sheet1,Sheet2等等)。你可以在任何时候使用 Worksheet.title 这个属性来改变它的名称。

TempSht.title = "NewSheet"
  • 这一点其实非常类似VB中获取Sheet名称的方法,也是通过属性。不过VB用的是 .Name,在Python的openpyxl中,使用的是 .title。

The background color of the tab holding this title is white by default. You can change this providing an RRGGBB color code to the Worksheet.sheet_properties.tabColor attribute.
界面上承载工作表名称的tab按钮默认是白色背景。你可以通过改变 Worksheet.sheet_properties.tabColor 属性的RRGGBB(RGB代码)来改变颜色。

TempSht.sheet_properties.tabColor = "1072BA"
  • 这个功能其实还是比较辅助性的,虽然对于数据来说没有决定性的作用,但至少是增加了一种区别数据的途径,还是相当不错的。

Once you gave a worksheet a name, you can get it as a key of the workbook.
一旦你给一张工作表取了名字,那么你就可以在这个工作簿中通过名字来索引到这张表。

sht = wb["TempSht"]
  • 其实,这点python与vb有很大的区别呢:
    • 在vb中,通过名称来索引工作表通常是 ThisWorkbook.sheets(“TempSht”) 或者 Set wb = ActiveWorkbook ⇒ sht = wb.sheets(“TempSht”) 这类
    • 在python中,则是直接在 wb 当中去定位,并没有 sheets 这样的集合;即 workbook ⇒ worksheet,中间不再有sheets这个中间层的感觉吧!

这点在接下来的部分也能够感受到。

You can review the names of all worksheets of the workbook with the Workbook.sheetname attribute.
你可以通过 Workbook.sheetname 来查看整个工作簿所有工作表的名称。

>>> print(wb.sheetnames)
['Sheet2', 'New Title', 'Sheet1']

You can loop through worksheets.
你也可以在所有工作表中进行循环操作。

>>> for sheet in wb:
...     print(sheet.title)
  • 在这里,就很类似VB中遍览所有sheet来做指定操作的方式(for循环)

You can create copies of worksheets within a single workbook: Workbook.copy_worksheet() method.
你可以在一个工作簿中通过 Workbook.copy_worksheet() 方法来复制工作表。

source = wb.active
target = wb.copy_worksheet(source)

—— Note ——
Only cells (including values, styles, hyperlinks and comments) and certain worksheet attribues (including dimensions, format and properties) are copied. All other workbook / worksheet attributes are not copied - e.g. Images, Charts.
复制的仅仅是单元格(包括值、样式、超链接以及注释)和特定的工作表属性(包括范围、格式和属性)。其他工作簿或工作表属性是不会被复制的,例如图片、图表。
You also cannot copy worksheets between workbooks. You cannot copy a worksheet if the workbook is open in read-only or write-only mode.
在多个工作簿中是无法通过这个方法来复制工作表的。另外,一个以只读或只写模式打开的工作簿也不能通过这个方法来复制工作表。


02 处理数据(Playing with data)

02.1 获取单个单元格(Accessing one cell)

Now we know how to get a worksheet, we can start modifying cells content. Cells can be accessed directly as keys of the worksheet.
既然我们知道了如何去定位一张工作表,那么就可以开始修改单元格内容了。所有单元格都可以直接通过工作表索引来获取。

c = TempSht['A4']

This will return the cell at A4, or create one if it does not exist yet. Values can be directly assigned.
如此就会将A4单元格返回到变量中,或者当不存在A4时(也就是A4单元格还未被使用的情况下)创建一个。它的值可以直接被赋予,如下。

TempSht['A4'] = 42

There is also the Worksheet.cell() method.
This provides access to cells using row and column notation:
这边也存在 Worksheet.cell() 方法,以此来通过行、列来获取单元格。

d = TempSht.cell(row=4, column=2, value=10)

—— Note ——
When a worksheet is created in memory, it contains no cells. They are created when first accessed.
当一个工作表在内存中被创建时,它实际上是没有单元格的(若直接使用MSOffice Excel,这些单元格被认为是没有被使用的,VB中也有类似情况)。单元格会在第一次被获取的时候进行创建。

—— Warning ——
Because of this feature, scrolling through cells instead of accessing them directly will create them all in memory, even if you don’t assign them a value.
因此用检视所有单元格的方法来代替直接获取他们将会导致所有单元格在内存中被创建,即便你根本没有给他们赋值。


Something like this will create 100×100 cells in memory, for nothing.
例如下面这段检视将会在内存中创建100×100范围的单元格,却无任何用处。

>>> for x in range(1,101):
...    for y in range(1,101):
...        ws.cell(row=x, column=y)

02.2 获取多个单元格(Accessing many cells)

Ranges of cells can be accessed using slicing.
单元格的范围可以通过切片来获取。

cell_range = TempSht['A1':'C2']
  • VB中的range与python的range还是有很大区别呐!= =+
  • Excel中,若是要取得范围,主要还是通过 cells 以及 range 函数来进行的,但实际上 openpyxl 的范围获取依然是基于 worksheet 的——总觉得 python 这边的操作已经省略掉了大量的中间集合,例如 worksheets, cells 这类。

Ranges of rows or columns can be obtained similarly.
整行整列的获取方法也很类似。

colC = sht['C']
col_range = sht['C:D']
row10 = sht[10]
row_range = sht[5:10]
  • 这里也是直接取代了VB中的 Columns 以及 Rows 函数,其实总觉得更方便了?一切都从 worksheet 中获取,要什么就切出来多少,不用过多关心要使用什么函数。

You can also use the Worksheet.iter_rows() method.
此外,你还可以使用 Worksheet.iter_rows() 方法来获取范围内的单元格。
– row iteration 行迭代

>>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
...    for cell in row:
...        print(cell)
<Cell Sheet1.A1>
<Cell Sheet1.B1>
<Cell Sheet1.C1>
<Cell Sheet1.A2>
<Cell Sheet1.B2>
<Cell Sheet1.C2>

Likewise the Worksheet.iter_cols() method will return columns.
类似的 Worksheets.iter_cols() 方法会返回列。

>>> for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
...     for cell in col:
...         print(cell)
<Cell Sheet1.A1>
<Cell Sheet1.A2>
<Cell Sheet1.B1>
<Cell Sheet1.B2>
<Cell Sheet1.C1
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值