25.md 20.4 KB
Newer Older
W
wizardforcel 已提交
1
# OpenPyXL 教程
W
wizardforcel 已提交
2 3 4

> 原文: [http://zetcode.com/python/openpyxl/](http://zetcode.com/python/openpyxl/)

W
wizardforcel 已提交
5
在本教程中,我们展示如何使用 OpenPyXL 库在 Python 中使用 Excel 文件。
W
wizardforcel 已提交
6

W
wizardforcel 已提交
7
## OpenPyXL
W
wizardforcel 已提交
8

W
wizardforcel 已提交
9
OpenPyXL 是用于读取和写入 Excel 2010 xlsx/xlsm/xltx/xltm 文件的 Python 库。
W
wizardforcel 已提交
10 11 12 13 14

## Excel xlsx

在本教程中,我们使用 xlsx 文件。 xlsx 是 Microsoft Excel 使用的开放 XML 电子表格文件格式的文件扩展名。 xlsm 文件支持宏。 xlsx 是专有的二进制格式,而 xlsx 是基于 Office Open XML 格式的。

W
wizardforcel 已提交
15
```py
W
wizardforcel 已提交
16 17 18 19
$ sudo pip3 install openpyxl

```

W
wizardforcel 已提交
20
我们使用`pip3`工具安装 OpenPyXL。
W
wizardforcel 已提交
21

W
wizardforcel 已提交
22
## OpenPyXL 创建新文件
W
wizardforcel 已提交
23

W
wizardforcel 已提交
24
在第一个示例中,我们使用 OpenPyXL 创建一个新的 xlsx 文件。
W
wizardforcel 已提交
25 26 27

`write_xlsx.py`

W
wizardforcel 已提交
28
```py
W
wizardforcel 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#!/usr/bin/env python

from openpyxl import Workbook
import time

book = Workbook()
sheet = book.active

sheet['A1'] = 56
sheet['A2'] = 43

now = time.strftime("%x")
sheet['A3'] = now

book.save("sample.xlsx")

```

在示例中,我们创建一个新的 xlsx 文件。 我们将数据写入三个单元格。

W
wizardforcel 已提交
49
```py
W
wizardforcel 已提交
50 51 52 53
from openpyxl import Workbook

```

W
wizardforcel 已提交
54
从 OpenPyXL 模块,我们导入`Workbook`类。 工作簿是文档所有其他部分的容器。
W
wizardforcel 已提交
55

W
wizardforcel 已提交
56
```py
W
wizardforcel 已提交
57 58 59 60 61 62
book = Workbook()

```

我们创建一个新的工作簿。 始终使用至少一个工作表创建一个工作簿。

W
wizardforcel 已提交
63
```py
W
wizardforcel 已提交
64 65 66 67 68 69
sheet = book.active

```

我们获得对活动工作表的引用。

W
wizardforcel 已提交
70
```py
W
wizardforcel 已提交
71 72 73 74 75
sheet['A1'] = 56
sheet['A2'] = 43

```

W
wizardforcel 已提交
76
我们将数值数据写入单元格`A1``A2`
W
wizardforcel 已提交
77

W
wizardforcel 已提交
78
```py
W
wizardforcel 已提交
79 80 81 82 83
now = time.strftime("%x")
sheet['A3'] = now

```

W
wizardforcel 已提交
84
我们将当前日期写入单元格`A3`
W
wizardforcel 已提交
85

W
wizardforcel 已提交
86
```py
W
wizardforcel 已提交
87 88 89 90 91 92 93 94
book.save("sample.xlsx")

```

我们使用`save()`方法将内容写入`sample.xlsx`文件。

![New file](img/46dc21c705f99657d756ea6ced587768.jpg)

W
wizardforcel 已提交
95
图:新文件
W
wizardforcel 已提交
96

W
wizardforcel 已提交
97
## OpenPyXL 写入单元格
W
wizardforcel 已提交
98

W
wizardforcel 已提交
99
写入单元格有两种基本方法:使用工作表的键(例如`A1``D3`),或通过`cell()`方法使用行和列表示法。
W
wizardforcel 已提交
100 101 102

`write2cell.py`

W
wizardforcel 已提交
103
```py
W
wizardforcel 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
#!/usr/bin/env python

from openpyxl import Workbook

book = Workbook()
sheet = book.active

sheet['A1'] = 1
sheet.cell(row=2, column=2).value = 2

book.save('write2cell.xlsx')

```

在示例中,我们将两个值写入两个单元格。

W
wizardforcel 已提交
120
```py
W
wizardforcel 已提交
121 122 123 124
sheet['A1'] = 1

```

W
wizardforcel 已提交
125
在这里,我们将数值分配给`A1`单元。
W
wizardforcel 已提交
126

W
wizardforcel 已提交
127
```py
W
wizardforcel 已提交
128 129 130 131
sheet.cell(row=2, column=2).value = 2

```

W
wizardforcel 已提交
132
在这一行中,我们用行和列表示法写入单元格`B2`
W
wizardforcel 已提交
133

W
wizardforcel 已提交
134
## OpenPyXL 附加值
W
wizardforcel 已提交
135 136 137 138 139

使用`append()`方法,我们可以在当前工作表的底部附加一组值。

`appending_values.py`

W
wizardforcel 已提交
140
```py
W
wizardforcel 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
#!/usr/bin/env python

from openpyxl import Workbook

book = Workbook()
sheet = book.active

rows = (
    (88, 46, 57),
    (89, 38, 12),
    (23, 59, 78),
    (56, 21, 98),
    (24, 18, 43),
    (34, 15, 67)
)

for row in rows:
    sheet.append(row)

book.save('appending.xlsx')

```

在示例中,我们将三列数据附加到当前工作表中。

W
wizardforcel 已提交
166
```py
W
wizardforcel 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179
rows = (
    (88, 46, 57),
    (89, 38, 12),
    (23, 59, 78),
    (56, 21, 98),
    (24, 18, 43),
    (34, 15, 67)
)

```

数据存储在元组的元组中。

W
wizardforcel 已提交
180
```py
W
wizardforcel 已提交
181 182 183 184 185 186 187
for row in rows:
    sheet.append(row)

```

我们逐行浏览容器,并使用`append()`方法插入数据行。

W
wizardforcel 已提交
188
## OpenPyXL 读取单元格
W
wizardforcel 已提交
189 190 191 192 193

在下面的示例中,我们从`sample.xlsx`文件中读取先前写入的数据。

`read_cells.py`

W
wizardforcel 已提交
194
```py
W
wizardforcel 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
#!/usr/bin/env python

import openpyxl

book = openpyxl.load_workbook('sample.xlsx')

sheet = book.active

a1 = sheet['A1']
a2 = sheet['A2']
a3 = sheet.cell(row=3, column=1)

print(a1.value)
print(a2.value) 
print(a3.value)

```

该示例加载一个现有的 xlsx 文件并读取三个单元格。

W
wizardforcel 已提交
215
```py
W
wizardforcel 已提交
216 217 218 219 220 221
book = openpyxl.load_workbook('sample.xlsx')

```

使用`load_workbook()`方法打开文件。

W
wizardforcel 已提交
222
```py
W
wizardforcel 已提交
223 224 225 226 227 228
a1 = sheet['A1']
a2 = sheet['A2']
a3 = sheet.cell(row=3, column=1)

```

W
wizardforcel 已提交
229
我们读取`A1``A2``A3`单元的内容。 在第三行中,我们使用`cell()`方法获取`A3`单元格的值。
W
wizardforcel 已提交
230

W
wizardforcel 已提交
231
```py
W
wizardforcel 已提交
232 233 234 235 236 237 238 239 240
$ ./read_cells.py 
56
43
10/26/16

```

这是示例的输出。

W
wizardforcel 已提交
241
## OpenPyXL 读取多个单元格
W
wizardforcel 已提交
242 243 244 245 246

我们有以下数据表:

![Items](img/0a37bb76ecebbbab395c2cfdf903d43d.jpg)

W
wizardforcel 已提交
247
图:项目
W
wizardforcel 已提交
248 249 250 251 252

我们使用范围运算符读取数据。

`read_cells2.py`

W
wizardforcel 已提交
253
```py
W
wizardforcel 已提交
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
#!/usr/bin/env python

import openpyxl

book = openpyxl.load_workbook('items.xlsx')

sheet = book.active

cells = sheet['A1': 'B6']

for c1, c2 in cells:
    print("{0:8} {1:8}".format(c1.value, c2.value))

```

在示例中,我们使用范围运算从两列读取数据。

W
wizardforcel 已提交
271
```py
W
wizardforcel 已提交
272 273 274 275
cells = sheet['A1': 'B6']

```

W
wizardforcel 已提交
276
在这一行中,我们从单元格`A1-B6`中读取数据。
W
wizardforcel 已提交
277

W
wizardforcel 已提交
278
```py
W
wizardforcel 已提交
279 280 281 282 283 284 285
for c1, c2 in cells:
    print("{0:8} {1:8}".format(c1.value, c2.value))

```

`format()`功能用于在控制台上整洁地输出数据。

W
wizardforcel 已提交
286
```py
W
wizardforcel 已提交
287 288 289 290 291 292 293 294 295 296 297 298
$ ./read_cells2.py 
Items    Quantity
coins          23
chairs          3
pencils         5
bottles         8
books          30

```

这是程序的输出。

W
wizardforcel 已提交
299
## OpenPyXL 按行迭代
W
wizardforcel 已提交
300 301 302 303 304

`iter_rows()`方法将工作表中的单元格返回为行。

`iterating_by_rows.py`

W
wizardforcel 已提交
305
```py
W
wizardforcel 已提交
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
#!/usr/bin/env python

from openpyxl import Workbook

book = Workbook()
sheet = book.active

rows = (
    (88, 46, 57),
    (89, 38, 12),
    (23, 59, 78),
    (56, 21, 98),
    (24, 18, 43),
    (34, 15, 67)
)

for row in rows:
    sheet.append(row)

for row in sheet.iter_rows(min_row=1, min_col=1, max_row=6, max_col=3):
    for cell in row:
        print(cell.value, end=" ")
    print()    

book.save('iterbyrows.xlsx')

```

该示例逐行遍历数据。

W
wizardforcel 已提交
336
```py
W
wizardforcel 已提交
337 338 339 340 341 342
for row in sheet.iter_rows(min_row=1, min_col=1, max_row=6, max_col=3):

```

我们提供了迭代的边界。

W
wizardforcel 已提交
343
```py
W
wizardforcel 已提交
344 345 346 347 348 349 350 351 352 353 354 355
$ ./iterating_by_rows.py 
88 46 57 
89 38 12 
23 59 78 
56 21 98 
24 18 43 
34 15 67 

```

这是示例的输出。

W
wizardforcel 已提交
356
## OpenPyXL 按列迭代
W
wizardforcel 已提交
357 358 359 360 361

`iter_cols()`方法将工作表中的单元格作为列返回。

`iterating_by_columns.py`

W
wizardforcel 已提交
362
```py
W
wizardforcel 已提交
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
#!/usr/bin/env python

from openpyxl import Workbook

book = Workbook()
sheet = book.active

rows = (
    (88, 46, 57),
    (89, 38, 12),
    (23, 59, 78),
    (56, 21, 98),
    (24, 18, 43),
    (34, 15, 67)
)

for row in rows:
    sheet.append(row)

for row in sheet.iter_cols(min_row=1, min_col=1, max_row=6, max_col=3):
    for cell in row:
        print(cell.value, end=" ")
    print()    

book.save('iterbycols.xlsx')

```

该示例逐列遍历数据。

W
wizardforcel 已提交
393
```py
W
wizardforcel 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
$ ./iterating_by_columns.py 
88 89 23 56 24 34 
46 38 59 21 18 15 
57 12 78 98 43 67 

```

这是示例的输出。

## 统计

对于下一个示例,我们需要创建一个包含数字的 xlsx 文件。 例如,我们使用`RANDBETWEEN()`函数在 10 列中创建了 25 行数字。

`mystats.py`

W
wizardforcel 已提交
409
```py
W
wizardforcel 已提交
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
#!/usr/bin/env python

import openpyxl
import statistics as stats

book = openpyxl.load_workbook('numbers.xlsx', data_only=True)

sheet = book.active

rows = sheet.rows

values = []

for row in rows:
    for cell in row:
        values.append(cell.value)

print("Number of values: {0}".format(len(values)))
print("Sum of values: {0}".format(sum(values)))
print("Minimum value: {0}".format(min(values)))
print("Maximum value: {0}".format(max(values)))
print("Mean: {0}".format(stats.mean(values)))
print("Median: {0}".format(stats.median(values)))
print("Standard deviation: {0}".format(stats.stdev(values)))
print("Variance: {0}".format(stats.variance(values)))

```

在示例中,我们从工作表中读取所有值并计算一些基本统计信息。

W
wizardforcel 已提交
440
```py
W
wizardforcel 已提交
441 442 443 444 445 446
import statistics as stats

```

导入`statistics`模块以提供一些统计功能,例如中值和方差。

W
wizardforcel 已提交
447
```py
W
wizardforcel 已提交
448 449 450 451 452 453
book = openpyxl.load_workbook('numbers.xlsx', data_only=True)

```

使用`data_only`选项,我们从单元格而不是公式中获取值。

W
wizardforcel 已提交
454
```py
W
wizardforcel 已提交
455 456 457 458 459 460
rows = sheet.rows

```

我们得到所有不为空的单元格行。

W
wizardforcel 已提交
461
```py
W
wizardforcel 已提交
462 463 464 465 466 467
for row in rows:
    for cell in row:
        values.append(cell.value)

```

W
wizardforcel 已提交
468
在两个`for`循环中,我们从单元格中形成一个整数值列表。
W
wizardforcel 已提交
469

W
wizardforcel 已提交
470
```py
W
wizardforcel 已提交
471 472 473 474 475 476 477 478 479 480 481 482 483
print("Number of values: {0}".format(len(values)))
print("Sum of values: {0}".format(sum(values)))
print("Minimum value: {0}".format(min(values)))
print("Maximum value: {0}".format(max(values)))
print("Mean: {0}".format(stats.mean(values)))
print("Median: {0}".format(stats.median(values)))
print("Standard deviation: {0}".format(stats.stdev(values)))
print("Variance: {0}".format(stats.variance(values)))

```

我们计算并打印有关值的数学统计信息。 一些功能是内置的,其他功能是通过`statistics`模块导入的。

W
wizardforcel 已提交
484
```py
W
wizardforcel 已提交
485 486 487 488 489 490 491 492 493 494 495 496 497 498
$ ./mystats.py 
Number of values: 312
Sum of values: 15877
Minimum value: 0
Maximum value: 100
Mean: 50.88782051282051
Median: 54.0
Standard deviation: 28.459203819700967
Variance: 809.9262820512821

```

这是一个示例输出。

W
wizardforcel 已提交
499
## OpenPyXL 过滤器&排序数据
W
wizardforcel 已提交
500 501 502

图纸具有`auto_filter`属性,该属性允许设置过滤条件和排序条件。

W
wizardforcel 已提交
503
请注意,OpenPyXL 设置了条件,但是我们必须在电子表格应用中应用它们。
W
wizardforcel 已提交
504 505 506

`filter_sort.py`

W
wizardforcel 已提交
507
```py
W
wizardforcel 已提交
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
#!/usr/bin/env python

from openpyxl import Workbook

wb = Workbook()
sheet = wb.active

data = [
    ['Item', 'Colour'],
    ['pen', 'brown'],
    ['book', 'black'],
    ['plate', 'white'],
    ['chair', 'brown'],
    ['coin', 'gold'],
    ['bed', 'brown'],
    ['notebook', 'white'],
]

for r in data:
    sheet.append(r)

sheet.auto_filter.ref = 'A1:B8'
sheet.auto_filter.add_filter_column(1, ['brown', 'white'])
sheet.auto_filter.add_sort_condition('B2:B8')

wb.save('filtered.xlsx')

```

在示例中,我们创建一个包含项目及其颜色的工作表。 我们设置一个过滤器和一个排序条件。

W
wizardforcel 已提交
539
## OpenPyXL 维度
W
wizardforcel 已提交
540 541 542 543 544

为了获得那些实际包含数据的单元格,我们可以使用维度。

`dimensions.py`

W
wizardforcel 已提交
545
```py
W
wizardforcel 已提交
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
#!/usr/bin/env python

from openpyxl import Workbook

book = Workbook()
sheet = book.active

sheet['A3'] = 39
sheet['B3'] = 19

rows = [
    (88, 46),
    (89, 38),
    (23, 59),
    (56, 21),
    (24, 18),
    (34, 15)
]

for row in rows:
    sheet.append(row)

print(sheet.dimensions)
print("Minimum row: {0}".format(sheet.min_row))
print("Maximum row: {0}".format(sheet.max_row))
print("Minimum column: {0}".format(sheet.min_column))
print("Maximum column: {0}".format(sheet.max_column))

for c1, c2 in sheet[sheet.dimensions]:
    print(c1.value, c2.value)

book.save('dimensions.xlsx')

```

该示例计算两列数据的维数。

W
wizardforcel 已提交
583
```py
W
wizardforcel 已提交
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
sheet['A3'] = 39
sheet['B3'] = 19

rows = [
    (88, 46),
    (89, 38),
    (23, 59),
    (56, 21),
    (24, 18),
    (34, 15)
]

for row in rows:
    sheet.append(row)

```

我们将数据添加到工作表。 请注意,我们从第三行开始添加。

W
wizardforcel 已提交
603
```py
W
wizardforcel 已提交
604 605 606 607 608 609
print(sheet.dimensions)

```

`dimensions`属性返回非空单元格区域的左上角和右下角单元格。

W
wizardforcel 已提交
610
```py
W
wizardforcel 已提交
611 612 613 614 615 616 617
print("Minimum row: {0}".format(sheet.min_row))
print("Maximum row: {0}".format(sheet.max_row))

```

使用`min_row``max_row`属性,我们可以获得包含数据的最小和最大行。

W
wizardforcel 已提交
618
```py
W
wizardforcel 已提交
619 620 621 622 623 624 625
print("Minimum column: {0}".format(sheet.min_column))
print("Maximum column: {0}".format(sheet.max_column))

```

通过`min_column``max_column`属性,我们获得了包含数据的最小和最大列。

W
wizardforcel 已提交
626
```py
W
wizardforcel 已提交
627 628 629 630 631 632 633
for c1, c2 in sheet[sheet.dimensions]:
    print(c1.value, c2.value)

```

我们遍历数据并将其打印到控制台。

W
wizardforcel 已提交
634
```py
W
wizardforcel 已提交
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
$ ./dimensions.py 
A3:B9
Minimum row: 3
Maximum row: 9
Minimum column: 1
Maximum column: 2
39 19
88 46
89 38
23 59
56 21
24 18
34 15

```

这是示例的输出。

W
wizardforcel 已提交
653
## 工作表
W
wizardforcel 已提交
654 655 656 657 658

每个工作簿可以有多个工作表。

![Sheets](img/4bf58174c38e97e6f35cd58e9c9433d1.jpg)

W
wizardforcel 已提交
659
图:床单
W
wizardforcel 已提交
660 661 662 663 664

让我们有一张包含这三张纸的工作簿。

`sheets.py`

W
wizardforcel 已提交
665
```py
W
wizardforcel 已提交
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
#!/usr/bin/env python

import openpyxl

book = openpyxl.load_workbook('sheets.xlsx')

print(book.get_sheet_names())

active_sheet = book.active
print(type(active_sheet))

sheet = book.get_sheet_by_name("March")
print(sheet.title)

```

该程序可用于 Excel 工作表。

W
wizardforcel 已提交
684
```py
W
wizardforcel 已提交
685 686 687 688 689 690
print(book.get_sheet_names())

```

`get_sheet_names()`方法返回工作簿中可用工作表的名称。

W
wizardforcel 已提交
691
```py
W
wizardforcel 已提交
692 693 694 695 696 697 698
active_sheet = book.active
print(type(active_sheet))

```

我们获取活动表并将其类型打印到终端。

W
wizardforcel 已提交
699
```py
W
wizardforcel 已提交
700 701 702 703 704 705
sheet = book.get_sheet_by_name("March")

```

我们使用`get_sheet_by_name()`方法获得对工作表的引用。

W
wizardforcel 已提交
706
```py
W
wizardforcel 已提交
707 708 709 710 711 712
print(sheet.title)

```

检索到的工作表的标题将打印到终端。

W
wizardforcel 已提交
713
```py
W
wizardforcel 已提交
714 715 716 717 718 719 720 721 722 723 724
$ ./sheets.py 
['January', 'February', 'March']
<class 'openpyxl.worksheet.worksheet.Worksheet'>
March

```

这是程序的输出。

`sheets2.py`

W
wizardforcel 已提交
725
```py
W
wizardforcel 已提交
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
#!/usr/bin/env python

import openpyxl

book = openpyxl.load_workbook('sheets.xlsx')

book.create_sheet("April")

print(book.sheetnames)

sheet1 = book.get_sheet_by_name("January")
book.remove_sheet(sheet1)

print(book.sheetnames)

book.create_sheet("January", 0)
print(book.sheetnames)

book.save('sheets2.xlsx')

```

在此示例中,我们创建一个新工作表。

W
wizardforcel 已提交
750
```py
W
wizardforcel 已提交
751 752 753 754 755 756
book.create_sheet("April")

```

使用`create_sheet()`方法创建一个新图纸。

W
wizardforcel 已提交
757
```py
W
wizardforcel 已提交
758 759 760 761 762 763
print(book.sheetnames)

```

图纸名称也可以使用`sheetnames`属性显示。

W
wizardforcel 已提交
764
```py
W
wizardforcel 已提交
765 766 767 768 769 770
book.remove_sheet(sheet1)

```

可以使用`remove_sheet()`方法将纸张取出。

W
wizardforcel 已提交
771
```py
W
wizardforcel 已提交
772 773 774 775 776 777
book.create_sheet("January", 0)

```

可以在指定位置创建一个新图纸。 在我们的例子中,我们在索引为 0 的位置创建一个新工作表。

W
wizardforcel 已提交
778
```py
W
wizardforcel 已提交
779 780 781 782 783 784 785 786 787 788 789 790 791
$ ./sheets2.py 
['January', 'February', 'March', 'April']
['February', 'March', 'April']
['January', 'February', 'March', 'April']

```

这是程序的输出。

可以更改工作表的背景颜色。

`sheets3.py`

W
wizardforcel 已提交
792
```py
W
wizardforcel 已提交
793 794 795 796 797 798 799 800 801 802 803 804 805
#!/usr/bin/env python

import openpyxl

book = openpyxl.load_workbook('sheets.xlsx')

sheet = book.get_sheet_by_name("March")
sheet.sheet_properties.tabColor = "0072BA"

book.save('sheets3.xlsx')

```

W
wizardforcel 已提交
806
该示例修改了标题为“`March`”的工作表的背景颜色。
W
wizardforcel 已提交
807

W
wizardforcel 已提交
808
```py
W
wizardforcel 已提交
809 810 811 812 813 814 815 816
sheet.sheet_properties.tabColor = "0072BA"

```

我们将`tabColor`属性更改为新颜色。

![Background colour of a worksheet](img/267940254c695254cc2b315f33c1d587.jpg)

W
wizardforcel 已提交
817
图:工作表的背景色
W
wizardforcel 已提交
818 819 820

第三工作表的背景色已更改为某种蓝色。

W
wizardforcel 已提交
821
## 合并单元格
W
wizardforcel 已提交
822 823 824 825 826

单元格可以使用`merge_cells()`方法合并,而可以不使用`unmerge_cells()`方法合并。 当我们合并单元格时,除了左上角的所有单元格都将从工作​​表中删除。

`merging_cells.py`

W
wizardforcel 已提交
827
```py
W
wizardforcel 已提交
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
#!/usr/bin/env python

from openpyxl import Workbook
from openpyxl.styles import Alignment

book = Workbook()
sheet = book.active

sheet.merge_cells('A1:B2')

cell = sheet.cell(row=1, column=1)
cell.value = 'Sunny day'
cell.alignment = Alignment(horizontal='center', vertical='center')

book.save('merging.xlsx')

```

W
wizardforcel 已提交
846
在该示例中,我们合并了四个单元格:`A1``B1``A2``B2`。 最后一个单元格中的文本居中。
W
wizardforcel 已提交
847

W
wizardforcel 已提交
848
```py
W
wizardforcel 已提交
849 850 851 852 853 854
from openpyxl.styles import Alignment

```

为了使文本在最后一个单元格中居中,我们使用了`openpyxl.styles`模块中的`Alignment`类。

W
wizardforcel 已提交
855
```py
W
wizardforcel 已提交
856 857 858 859 860 861
sheet.merge_cells('A1:B2')

```

我们用`merge_cells()`方法合并四个单元格。

W
wizardforcel 已提交
862
```py
W
wizardforcel 已提交
863 864 865 866 867 868
cell = sheet.cell(row=1, column=1)

```

我们得到了最后一个单元格。

W
wizardforcel 已提交
869
```py
W
wizardforcel 已提交
870 871 872 873 874 875 876 877 878
cell.value = 'Sunny day'
cell.alignment = Alignment(horizontal='center', vertical='center')

```

我们将文本设置为合并的单元格并更新其对齐方式。

![Merged cells](img/7b00cc20b247e6eabdfd52d679384005.jpg)

W
wizardforcel 已提交
879
图:合并的单元格
W
wizardforcel 已提交
880

W
wizardforcel 已提交
881
## OpenPyXL 冻结窗格
W
wizardforcel 已提交
882 883 884 885 886

冻结窗格时,在滚动到工作表的另一个区域时,我们会保持工作表的某个区域可见。

`freezing.py`

W
wizardforcel 已提交
887
```py
W
wizardforcel 已提交
888 889 890 891 892 893 894 895 896 897 898 899 900 901
#!/usr/bin/env python

from openpyxl import Workbook
from openpyxl.styles import Alignment

book = Workbook()
sheet = book.active

sheet.freeze_panes = 'B2'

book.save('freezing.xlsx')

```

W
wizardforcel 已提交
902
该示例通过单元格`B2`冻结窗格。
W
wizardforcel 已提交
903

W
wizardforcel 已提交
904
```py
W
wizardforcel 已提交
905 906 907 908 909 910
sheet.freeze_panes = 'B2'

```

要冻结窗格,我们使用`freeze_panes`属性。

W
wizardforcel 已提交
911
## OpenPyXL 公式
W
wizardforcel 已提交
912

W
wizardforcel 已提交
913
下一个示例显示如何使用公式。 OpenPyXL 不进行计算; 它将公式写入单元格。
W
wizardforcel 已提交
914 915 916

`formulas.py`

W
wizardforcel 已提交
917
```py
W
wizardforcel 已提交
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
#!/usr/bin/env python

from openpyxl import Workbook

book = Workbook()
sheet = book.active

rows = (
    (34, 26),
    (88, 36),
    (24, 29),
    (15, 22),
    (56, 13),
    (76, 18)
)

for row in rows:
    sheet.append(row)

cell = sheet.cell(row=7, column=2)
cell.value = "=SUM(A1:B6)"
cell.font = cell.font.copy(bold=True)

book.save('formulas.xlsx')

```

在示例中,我们使用`SUM()`函数计算所有值的总和,并以粗体显示输出样式。

W
wizardforcel 已提交
947
```py
W
wizardforcel 已提交
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
rows = (
    (34, 26),
    (88, 36),
    (24, 29),
    (15, 22),
    (56, 13),
    (76, 18)
)

for row in rows:
    sheet.append(row)

```

我们创建两列数据。

W
wizardforcel 已提交
964
```py
W
wizardforcel 已提交
965 966 967 968 969 970
cell = sheet.cell(row=7, column=2)

```

我们得到显示计算结果的单元格。

W
wizardforcel 已提交
971
```py
W
wizardforcel 已提交
972 973 974 975 976 977
cell.value = "=SUM(A1:B6)"

```

我们将一个公式写入单元格。

W
wizardforcel 已提交
978
```py
W
wizardforcel 已提交
979 980 981 982 983 984 985 986
cell.font = cell.font.copy(bold=True)

```

我们更改字体样式。

![Calculating the sum of values](img/330dc2c6f5e65fc37e8ed308b4c9405f.jpg)

W
wizardforcel 已提交
987
图:计算值之和
W
wizardforcel 已提交
988

W
wizardforcel 已提交
989
## OpenPyXL 图像
W
wizardforcel 已提交
990 991 992 993 994

在下面的示例中,我们显示了如何将图像插入到工作表中。

`write_image.py`

W
wizardforcel 已提交
995
```py
W
wizardforcel 已提交
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
#!/usr/bin/env python

from openpyxl import Workbook
from openpyxl.drawing.image import Image

book = Workbook()
sheet = book.active

img = Image("icesid.png")
sheet['A1'] = 'This is Sid'

sheet.add_image(img, 'B2')

book.save("sheet_image.xlsx")

```

在示例中,我们将图像写到一张纸上。

W
wizardforcel 已提交
1015
```py
W
wizardforcel 已提交
1016 1017 1018 1019 1020 1021
from openpyxl.drawing.image import Image

```

我们使用`openpyxl.drawing.image`模块中的`Image`类。

W
wizardforcel 已提交
1022
```py
W
wizardforcel 已提交
1023 1024 1025 1026 1027 1028
img = Image("icesid.png")

```

创建一个新的`Image`类。 `icesid.png`图像位于当前工作目录中。

W
wizardforcel 已提交
1029
```py
W
wizardforcel 已提交
1030 1031 1032 1033 1034 1035
sheet.add_image(img, 'B2')

```

我们使用`add_image()`方法添加新图像。

W
wizardforcel 已提交
1036
## OpenPyXL 图表
W
wizardforcel 已提交
1037

W
wizardforcel 已提交
1038
OpenPyXL 库支持创建各种图表,包括条形图,折线图,面积图,气泡图,散点图和饼图。
W
wizardforcel 已提交
1039

W
wizardforcel 已提交
1040
根据文档,OpenPyXL 仅支持在工作表中创建图表。 现有工作簿中的图表将丢失。
W
wizardforcel 已提交
1041 1042 1043

`create_bar_chart.py`

W
wizardforcel 已提交
1044
```py
W
wizardforcel 已提交
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
#!/usr/bin/env python

from openpyxl import Workbook
from openpyxl.chart import (
    Reference,
    Series,
    BarChart
)

book = Workbook()
sheet = book.active

rows = [
    ("USA", 46),
    ("China", 38),
    ("UK", 29),
    ("Russia", 22),
    ("South Korea", 13),
    ("Germany", 11)
]

for row in rows:
    sheet.append(row)

data = Reference(sheet, min_col=2, min_row=1, max_col=2, max_row=6)
categs = Reference(sheet, min_col=1, min_row=1, max_row=6)

chart = BarChart()
chart.add_data(data=data)
chart.set_categories(categs)

chart.legend = None
chart.y_axis.majorGridlines = None
chart.varyColors = True
chart.title = "Olympic Gold medals in London"

sheet.add_chart(chart, "A8")    

book.save("bar_chart.xlsx")

```

在此示例中,我们创建了一个条形图,以显示 2012 年伦敦每个国家/地区的奥运金牌数量。

W
wizardforcel 已提交
1089
```py
W
wizardforcel 已提交
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
from openpyxl.chart import (
    Reference,
    Series,
    BarChart
)

```

`openpyxl.chart`模块具有使用图表的工具。

W
wizardforcel 已提交
1100
```py
W
wizardforcel 已提交
1101 1102 1103 1104 1105 1106 1107
book = Workbook()
sheet = book.active

```

创建一个新的工作簿。

W
wizardforcel 已提交
1108
```py
W
wizardforcel 已提交
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
rows = [
    ("USA", 46),
    ("China", 38),
    ("UK", 29),
    ("Russia", 22),
    ("South Korea", 13),
    ("Germany", 11)
]

for row in rows:
    sheet.append(row)

```

我们创建一些数据并将其添加到活动工作表的单元格中。

W
wizardforcel 已提交
1125
```py
W
wizardforcel 已提交
1126 1127 1128 1129 1130 1131
data = Reference(sheet, min_col=2, min_row=1, max_col=2, max_row=6)

```

对于`Reference`类,我们引用表中代表数据的行。 在我们的案例中,这些是奥运金牌的数量。

W
wizardforcel 已提交
1132
```py
W
wizardforcel 已提交
1133 1134 1135 1136 1137 1138
categs = Reference(sheet, min_col=1, min_row=1, max_row=6)

```

我们创建一个类别轴。 类别轴是将数据视为一系列非数字文本标签的轴。 在我们的案例中,我们有代表国家名称的文本标签。

W
wizardforcel 已提交
1139
```py
W
wizardforcel 已提交
1140 1141 1142 1143 1144 1145 1146 1147
chart = BarChart()
chart.add_data(data=data)
chart.set_categories(categs)

```

我们创建一个条形图并为其设置数据和类别。

W
wizardforcel 已提交
1148
```py
W
wizardforcel 已提交
1149 1150 1151 1152 1153 1154 1155
chart.legend = None
chart.y_axis.majorGridlines = None

```

使用`legend``majorGridlines`属性,可以关闭图例和主要网格线。

W
wizardforcel 已提交
1156
```py
W
wizardforcel 已提交
1157 1158 1159 1160 1161 1162
chart.varyColors = True

```

`varyColors`设置为`True`,每个条形都有不同的颜色。

W
wizardforcel 已提交
1163
```py
W
wizardforcel 已提交
1164 1165 1166 1167 1168 1169
chart.title = "Olympic Gold medals in London"

```

为图表设置标题。

W
wizardforcel 已提交
1170
```py
W
wizardforcel 已提交
1171 1172 1173 1174 1175 1176 1177 1178
sheet.add_chart(chart, "A8")   

```

使用`add_chart()`方法将创建的图表添加到工作表中。

![Bar chart](img/3bf54c368a46a154e45200cfe08e019d.jpg)

W
wizardforcel 已提交
1179
图:条形图
W
wizardforcel 已提交
1180

W
wizardforcel 已提交
1181
在本教程中,我们使用了 OpenPyXL 库。 我们已经从 Excel 文件中读取数据,并将数据写入 Excel 文件中。
W
wizardforcel 已提交
1182

W
wizardforcel 已提交
1183
您可能也对以下相关教程感兴趣: [Python 教程](/lang/python/)[Python CSV 教程](/python/csv/)[Python SimpleJson 教程](/python/simplejson/)[Python 列表推导](/articles/pythonlistcomprehensions/)
W
wizardforcel 已提交
1184 1185

列出[所有 Python 教程](/all/#python)