Contents

Python-第三方库-Openpyxl

PYPI官网

官方文档

教程

创建工作簿

1
2
from openpyxl import Workbook
wb = Workbook()

获取默认Worksheet

1
ws = wb.active

创建新的Worksheet

1
Workbook.create_sheet()

修改Worksheet名称

1
ws.title = "New Title"

一旦为Worksheet命名,您就可以将其作为Workbook的键

1
ws3 = wb["New Title"]

查看该workbook的所有worksheet的名称

1
Workbook.sheetname

遍历该workbook的所有worksheet

1
2
for sheet in wb:
    ...

在workbook中创建worksheet副本

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

CRUD数据

访问一个单元格

1
c = ws['A4']

赋值单元格

1
ws['A4'] = 4

Worksheet.cell()方法

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

注意,worksheet创建时并不会在内存加载所有单元格,单元格只在访问的时候加载进内存

给cell赋值

1
c.value = 'hello, world'

批量访问单元格

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# 切片来访问单元格范围
cell_range = ws['A1':'C2']
# 行或列的范围
colC = ws['C']
col_range = ws['C:D']
row10 = ws[10]
row_range = ws[5:10]
# Worksheet.iter_rows()
for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
    for cell in row:
        ...
# Worksheet.iter_cols(),出于性能原因只读模式下不可用
for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
    for cell in col:
        ...

迭代文件的所有行或列:Worksheet.rows,Worksheet.columns(只读模式下不可用)

仅值:只返回值不返回单元格的其他信息

1
2
3
4
5
6
7
# Worksheet.values
for row in ws.values:
    for value in row:
      ...
# 将Worksheet.iter_rows()和Worksheet.iter_cols()的values_only参数设置为True
for row in ws.iter_rows(min_row=1, max_col=3, max_row=2, values_only=True):
    print(row)

数据存储

保存到文件

1
2
# 此操作将覆盖现有文件而不发出警告
wb.save('balances.xlsx')

保存为模板

1
2
wb.template=True
wb.save('document_template.xltx')

另存为流

1
2
3
4
5
6
7
from tempfile import NamedTemporaryFile
from openpyxl import Workbook
wb = Workbook()
with NamedTemporaryFile() as tmp:
    wb.save(tmp.name)
    tmp.seek(0)
    stream = tmp.read()

从文件加载

1
wb = load_workbook(filename = 'empty_book.xlsx')
 |