25.md 20.3 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 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 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 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 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 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 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 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
# OpenPyXL 教程

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

在本教程中,我们展示如何使用 openpyxl 库在 Python 中使用 Excel 文件。

## Openpyxl

openpyxl 是用于读取和写入 Excel 2010 xlsx / xlsm / xltx / xltm 文件的 Python 库。

## Excel xlsx

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

```
$ sudo pip3 install openpyxl

```

我们使用`pip3`工具安装`openpyxl`

## Openpyxl 创建新文件

在第一个示例中,我们使用`openpyxl`创建一个新的 xlsx 文件。

`write_xlsx.py`

```
#!/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 文件。 我们将数据写入三个单元格。

```
from openpyxl import Workbook

```

`openpyxl`模块,我们导入`Workbook`类。 工作簿是文档所有其他部分的容器。

```
book = Workbook()

```

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

```
sheet = book.active

```

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

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

```

我们将数值数据写入单元格 A1 和 A2。

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

```

我们将当前日期写入单元格 A3。

```
book.save("sample.xlsx")

```

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

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

Figure: New file

## Openpyxl 写入单元格

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

`write2cell.py`

```
#!/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')

```

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

```
sheet['A1'] = 1

```

在这里,我们将数值分配给 A1 单元。

```
sheet.cell(row=2, column=2).value = 2

```

在这一行中,我们用行和列表示法写入单元格 B2。

## Openpyxl 附加值

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

`appending_values.py`

```
#!/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')

```

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

```
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)

```

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

## OpenPyXL 读取单元格

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

`read_cells.py`

```
#!/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 文件并读取三个单元格。

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

```

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

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

```

我们读取 A1,A2 和 A3 单元的内容。 在第三行中,我们使用`cell()`方法获取 A3 单元格的值。

```
$ ./read_cells.py 
56
43
10/26/16

```

这是示例的输出。

## OpenPyXL 读取多个单元格

我们有以下数据表:

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

Figure: Items

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

`read_cells2.py`

```
#!/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))

```

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

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

```

在这一行中,我们从单元格 A1-B6 中读取数据。

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

```

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

```
$ ./read_cells2.py 
Items    Quantity
coins          23
chairs          3
pencils         5
bottles         8
books          30

```

这是程序的输出。

## Openpyxl 按行迭代

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

`iterating_by_rows.py`

```
#!/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')

```

该示例逐行遍历数据。

```
for row in sheet.iter_rows(min_row=1, min_col=1, max_row=6, max_col=3):

```

我们提供了迭代的边界。

```
$ ./iterating_by_rows.py 
88 46 57 
89 38 12 
23 59 78 
56 21 98 
24 18 43 
34 15 67 

```

这是示例的输出。

## Openpyxl 按列迭代

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

`iterating_by_columns.py`

```
#!/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')

```

该示例逐列遍历数据。

```
$ ./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`

```
#!/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)))

```

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

```
import statistics as stats

```

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

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

```

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

```
rows = sheet.rows

```

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

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

```

在两个 for 循环中,我们从单元格中形成一个整数值列表。

```
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`模块导入的。

```
$ ./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

```

这是一个示例输出。

## Openpyxl 过滤器&排序数据

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

请注意,Openpyxl 设置了条件,但是我们必须在电子表格应用程序中应用它们。

`filter_sort.py`

```
#!/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 545 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 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652

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

`dimensions.py`

```
#!/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')

```

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

```
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)

```

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

```
print("Minimum row: {0}".format(sheet.min_row))
print("Maximum row: {0}".format(sheet.max_row))

```

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

```
print("Minimum column: {0}".format(sheet.min_column))
print("Maximum column: {0}".format(sheet.max_column))

```

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

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

```

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

```
$ ./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 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820

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

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

Figure: Sheets

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

`sheets.py`

```
#!/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 工作表。

```
print(book.get_sheet_names())

```

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

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

```

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

```
sheet = book.get_sheet_by_name("March")

```

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

```
print(sheet.title)

```

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

```
$ ./sheets.py 
['January', 'February', 'March']
<class 'openpyxl.worksheet.worksheet.Worksheet'>
March

```

这是程序的输出。

`sheets2.py`

```
#!/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')

```

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

```
book.create_sheet("April")

```

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

```
print(book.sheetnames)

```

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

```
book.remove_sheet(sheet1)

```

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

```
book.create_sheet("January", 0)

```

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

```
$ ./sheets2.py 
['January', 'February', 'March', 'April']
['February', 'March', 'April']
['January', 'February', 'March', 'April']

```

这是程序的输出。

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

`sheets3.py`

```
#!/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')

```

该示例修改了标题为“ March”的工作表的背景颜色。

```
sheet.sheet_properties.tabColor = "0072BA"

```

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

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

Figure: Background colour of a worksheet

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

W
wizardforcel 已提交
821
## 合并单元格
W
wizardforcel 已提交
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 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 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 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 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185

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

`merging_cells.py`

```
#!/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')

```

在该示例中,我们合并了四个单元格:A1,B1,A2 和 B2。 最后一个单元格中的文本居中。

```
from openpyxl.styles import Alignment

```

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

```
sheet.merge_cells('A1:B2')

```

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

```
cell = sheet.cell(row=1, column=1)

```

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

```
cell.value = 'Sunny day'
cell.alignment = Alignment(horizontal='center', vertical='center')

```

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

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

Figure: Merged cells

## Openpyxl 冻结窗格

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

`freezing.py`

```
#!/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')

```

该示例通过单元格 B2 冻结窗格。

```
sheet.freeze_panes = 'B2'

```

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

## Openpyxl 公式

下一个示例显示如何使用公式。 `openpyxl`不进行计算; 它将公式写入单元格。

`formulas.py`

```
#!/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()`函数计算所有值的总和,并以粗体显示输出样式。

```
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)

```

我们更改字体样式。

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

Figure: Calculating the sum of values

## OpenPyXL 图像

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

`write_image.py`

```
#!/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")

```

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

```
from openpyxl.drawing.image import Image

```

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

```
img = Image("icesid.png")

```

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

```
sheet.add_image(img, 'B2')

```

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

## Openpyxl 图表

`openpyxl`库支持创建各种图表,包括条形图,折线图,面积图,气泡图,散点图和饼图。

根据文档,`openpyxl`仅支持在工作表中创建图表。 现有工作簿中的图表将丢失。

`create_bar_chart.py`

```
#!/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 年伦敦每个国家/地区的奥运金牌数量。

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

```

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

```
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)

```

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

```
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

```

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

```
chart.varyColors = True

```

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

```
chart.title = "Olympic Gold medals in London"

```

为图表设置标题。

```
sheet.add_chart(chart, "A8")   

```

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

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

Figure: Bar chart

在本教程中,我们使用了 openpyxl 库。 我们已经从 Excel 文件中读取数据,并将数据写入 Excel 文件中。

您可能也对以下相关教程感兴趣: [Python 教程](/lang/python/)[Python CSV 教程](/python/csv/)[Python simplejson 教程](/python/simplejson/)[Python 列表推导](/articles/pythonlistcomprehensions/)

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