Python 自动化运维与爬虫 · 篇5 · 中级
← 上篇:运维自动化:脚本与定时任务   |   系列完结 ✓

办公自动化:Excel、Word与PDF处理

让Python替你完成那些重复的办公文档工作
每月底整理销售数据、生成月度报告、合并PDF合同……这些重复性的办公文档工作消耗了大量时间。好消息是,Python 有完善的库来操作 Excel、Word 和 PDF 文件,一旦写好自动化脚本,以后每月只需运行一次脚本就能完成以前需要几小时的工作。本篇是本系列的最后一篇,将系统讲解 openpyxl(Excel)、python-docx(Word)和 PyPDF2/PdfPlumber(PDF)的使用方法,并最终实现"从 Excel 数据自动生成 Word 月度报告"的完整工作流。
目录
01办公自动化概述
02openpyxl:创建与写入Excel
03openpyxl:读取数据与公式
04openpyxl:图表与样式
05python-docx:创建Word文档
06python-docx:样式与模板填充
07PDF处理:读取、合并、拆分
08实战:自动生成月度销售报告
09自动化工作流串联

01 · 办公自动化概述

办公自动化的核心理念是:把重复性工作交给程序,把创造性工作留给自己。Python 在办公自动化领域的主要工具箱如下:

文件格式 推荐库 安装命令
Excel (.xlsx) openpyxl pip install openpyxl
Word (.docx) python-docx pip install python-docx
PDF PyPDF2 / PdfPlumber pip install PyPDF2 pdfplumber

先一次性安装所有需要的库:

Shell 安装依赖
pip install openpyxl python-docx PyPDF2 pdfplumber

02 · openpyxl:创建与写入Excel

openpyxl 的核心概念是 Workbook(工作簿)→ Sheet(工作表)→ Cell(单元格)。让我们从一个简单的例子开始:

Python 创建Excel并写入数据
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
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, PatternFill

# 创建工作簿
wb = Workbook()
ws = wb.active # 获取默认工作表
ws.title = "销售数据" # 重命名工作表

# 写入表头
headers = ["月份", "产品", "销量", "单价", "总额"]
for col, header in enumerate(headers, 1):
cell = ws.cell(row=1, column=col, value=header)
cell.font = Font(bold=True, size=12)
cell.fill = PatternFill("solid", fgColor="2EC4B6")
cell.font = Font(bold=True, color="FFFFFF")
cell.alignment = Alignment(horizontal="center")

# 写入数据
data = [
["1月", "Python入门", 120, 69.9],
["1月", "数据分析", 85, 89.0],
["1月", "机器学习", 45, 129.0],
["2月", "Python入门", 135, 69.9],
["2月", "数据分析", 92, 89.0],
]

for row_idx, row_data in enumerate(data, 2):
for col_idx, value in enumerate(row_data, 1):
ws.cell(row=row_idx, column=col_idx, value=value)
# 用Excel公式计算总额
ws.cell(
row=row_idx, column=5,
value=f"=C{row_idx}*D{row_idx}"
)

# 调整列宽
ws.column_dimensions["A"].width = 10
ws.column_dimensions["B"].width = 18
ws.column_dimensions["C"].width = 8
ws.column_dimensions["D"].width = 10
ws.column_dimensions["E"].width = 12

# 保存文件
wb.save("sales_report.xlsx")
print("Excel文件创建完成!")
⚠️ 常见错误
openpyxl 只支持 .xlsx 格式(Excel 2007+),不支持老版的 .xls 格式。如果你需要处理 .xls 文件,请使用 xlrd 库。另外,保存前确保文件没有在 Excel 中打开,否则会报权限错误。

03 · openpyxl:读取数据与公式

读取已有的 Excel 文件并提取数据,是办公自动化中最常见的操作:

Python 读取Excel数据
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
from openpyxl import load_workbook

# 加载已有文件
wb = load_workbook("sales_report.xlsx")
ws = wb["销售数据"] # 按名称获取工作表

# 遍历所有行(跳过表头)
for row in ws.iter_rows(min_row=2, values_only=True):
month, product, qty, price, total = row
print(f"{month} | {product} | 销量:{qty} | 总额:{total}")

# 读取特定单元格
cell = ws["B2"]
print(f"单元格B2: {cell.value}")

# 获取数据统计
total_qty = sum(
row[2] for row in ws.iter_rows(
min_row=2, min_col=1,
max_col=3, values_only=True
)
)
print(f"总销量: {total_qty}")

# 注意:公式单元格的两种读取方式
# data_only=False(默认):读取公式本身 "=C2*D2"
# data_only=True:读取计算后的值(需要Excel先保存过)
wb2 = load_workbook("sales_report.xlsx", data_only=True)
ws2 = wb2["销售数据"]
print(f"计算后的总额: {ws2['E2'].value}")
💡 小贴士:data_only 参数的坑
使用 data_only=True 读取时,openpyxl 不会自己计算公式,它只读取 Excel 上次保存时缓存的值。如果文件是 Python 刚创建且从未在 Excel 中打开过,公式单元格的值可能是 None。解决方案:在 Python 中手动计算结果写入,而不是依赖 Excel 公式。

04 · openpyxl:图表与样式

在 Excel 中插入图表可以让数据更直观。openpyxl 支持柱状图、折线图、饼图等多种图表类型:

Python Excel图表生成
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from openpyxl.chart import BarChart, Reference

# 假设ws已经写入了月度销售数据
# 数据范围:A1:E6(含表头)

# 创建柱状图
chart = BarChart()
chart.type = "col" # 柱状图
chart.title = "月度销售趋势"
chart.y_axis.title = "销量"
chart.x_axis.title = "产品"
chart.style = 10 # 预设样式

# 设置数据引用
data_ref = Reference(ws, min_col=3, min_row=1, max_row=6)
cats_ref = Reference(ws, min_col=2, min_row=2, max_row=6)
chart.add_data(data_ref, titles_from_data=True)
chart.set_categories(cats_ref)

# 将图表插入工作表
ws.add_chart(chart, "G2")
wb.save("sales_with_chart.xlsx")

05 · python-docx:创建Word文档

python-docx 可以创建和修改 Word 文档。核心概念是 Document(文档)→ Paragraph(段落)/ Table(表格)/ Run(文本片段):

Python 创建Word文档
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
from docx import Document
from docx.shared import Pt, Inches, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH

# 创建文档
doc = Document()

# 添加标题
title = doc.add_heading("月度销售报告", level=0)
title.alignment = WD_ALIGN_PARAGRAPH.CENTER

# 添加段落
doc.add_paragraph("报告期间:2024年1月 - 2月")
doc.add_heading("一、销售概况", level=1)

# 添加带格式的文本
para = doc.add_paragraph()
run1 = para.add_run("本月总销售额为 ")
run2 = para.add_run("¥128,500")
run2.bold = True
run2.font.size = Pt(14)
run2.font.color.rgb = None # 使用主题色
run3 = para.add_run(",同比增长 ")
run4 = para.add_run("15.3%")
run4.font.color.rgb = None
run4.bold = True

# 添加表格
doc.add_heading("二、产品明细", level=1)
table = doc.add_table(rows=4, cols=4)
table.style = "Table Grid"

# 填充表头
headers = ["产品", "销量", "单价", "总额"]
for i, header in enumerate(headers):
table.rows[0].cells[i].text = header

# 填充数据
data = [
["Python入门", "120", "¥69.9", "¥8,388"],
["数据分析", "85", "¥89.0", "¥7,565"],
["机器学习", "45", "¥129.0", "¥5,805"],
]
for row_idx, row_data in enumerate(data, 1):
for col_idx, value in enumerate(row_data):
table.rows[row_idx].cells[col_idx].text = value

doc.save("monthly_report.docx")
print("Word报告生成完成!")

06 · python-docx:样式与模板填充

在实际工作中,更常见的做法是准备一个 Word 模板,然后用 Python 填充数据。这样可以保持公司的统一格式:

Python 模板填充
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
from docx import Document

def fill_template(template_path, output_path, data):
"""
填充Word模板中的占位符
模板中使用 {{key}} 作为占位符
"""
doc = Document(template_path)
# 替换段落中的占位符
for para in doc.paragraphs:
for key, value in data.items():
placeholder = "{{" + key + "}}"
if placeholder in para.text:
# 逐Run替换,保留原有格式
for run in para.runs:
if placeholder in run.text:
run.text = run.text.replace(
placeholder, str(value)
)
# 替换表格中的占位符
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
for key, value in data.items():
placeholder = "{{" + key + "}}"
if placeholder in cell.text:
cell.text = cell.text.replace(
placeholder, str(value)
)
doc.save(output_path)

# 使用示例
report_data = {
"report_date": "2024年2月",
"total_sales": "¥128,500",
"growth_rate": "15.3%",
"top_product": "Python入门",
"author": "数据分析部"
}
fill_template(
"template.docx",
"report_202402.docx",
report_data
)

07 · PDF处理:读取、合并、拆分

PDF 文件的处理在办公自动化中同样重要——合同合并、发票拆分、文本提取等都是高频需求:

Python PDF处理完整示例
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
import PyPDF2
import pdfplumber

# ========== 读取PDF文本 ==========
with open("contract.pdf", "rb") as f:
reader = PyPDF2.PdfReader(f)
print(f"总页数: {len(reader.pages)}")
# 提取第1页文本
text = reader.pages[0].extract_text()
print(f"第1页内容:\n{text[:200]}")

# ========== 用pdfplumber提取表格(更精准) ==========
with pdfplumber.open("report.pdf") as pdf:
page = pdf.pages[0]
tables = page.extract_tables()
for table in tables:
for row in table:
print(row)

# ========== 合并多个PDF ==========
merger = PyPDF2.PdfMerger()
pdf_files = ["part1.pdf", "part2.pdf", "part3.pdf"]

for pdf_file in pdf_files:
merger.append(pdf_file)

merger.write("merged_contract.pdf")
merger.close()
print("PDF合并完成!")

# ========== 拆分PDF ==========
with open("big_file.pdf", "rb") as f:
reader = PyPDF2.PdfReader(f)
# 每5页拆分为一个文件
for i in range(0, len(reader.pages), 5):
writer = PyPDF2.PdfWriter()
for page in reader.pages[i:i+5]:
writer.add_page(page)
output_name = f"split_{i//5 + 1}.pdf"
with open(output_name, "wb") as out:
writer.write(out)
print(f"已拆分: {output_name}")
💡 小贴士:PyPDF2 vs PdfPlumber
PyPDF2 适合 PDF 的合并、拆分、旋转等基本操作;PdfPlumber 在文本提取和表格提取方面更加精准,尤其适合从 PDF 中提取结构化数据。两者可以配合使用。

08 · 实战:自动生成月度销售报告

最后的重头戏:从 Excel 销售数据文件中读取数据,进行统计分析,然后自动生成一份格式美观的 Word 月度报告。这就是办公自动化的终极形态——一个脚本搞定整条流水线。

Python 完整实战:Excel→Word自动报告
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
from openpyxl import load_workbook
from docx import Document
from docx.shared import Pt, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
from collections import defaultdict
from datetime import datetime

def read_sales_data(excel_path):
"""从Excel读取销售数据并统计"""
wb = load_workbook(excel_path)
ws = wb.active
products = defaultdict(lambda: {
"qty": 0, "revenue": 0.0
})
for row in ws.iter_rows(min_row=2, values_only=True):
month, product, qty, price = row[:4]
revenue = qty * price
products[product]["qty"] += qty
products[product]["revenue"] += revenue
# 计算汇总
total_qty = sum(p["qty"] for p in products.values())
total_rev = sum(p["revenue"] for p in products.values())
return {
"products": dict(products),
"total_qty": total_qty,
"total_revenue": total_rev,
"product_count": len(products)
}

def generate_report(stats, output_path):
"""根据统计数据生成Word报告"""
doc = Document()
# 报告标题
title = doc.add_heading(
f"月度销售报告 - {datetime.now().strftime('%Y年%m月')}",
level=0
)
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 概览信息
doc.add_heading("一、销售概览", level=1)
doc.add_paragraph(
f"本期共销售 {stats['product_count']} 种产品,"
f"总销量 {stats['total_qty']} 件,"
f"总销售额 ¥{stats['total_revenue']:,.0f}。"
)
# 产品明细表格
doc.add_heading("二、产品明细", level=1)
# 按销售额降序排列
sorted_products = sorted(
stats["products"].items(),
key=lambda x: x[1]["revenue"],
reverse=True
)
table = doc.add_table(
rows=len(sorted_products) + 1,
cols=4
)
table.style = "Light Grid Accent 1"
# 表头
for i, h in enumerate(["产品", "销量", "销售额", "占比"]):
table.rows[0].cells[i].text = h
# 数据行
for idx, (name, data) in enumerate(sorted_products, 1):
pct = data["revenue"] / stats["total_revenue"] * 100
row = table.rows[idx]
row.cells[0].text = name
row.cells[1].text = str(data["qty"])
row.cells[2].text = f"¥{data['revenue']:,.0f}"
row.cells[3].text = f"{pct:.1f}%"
# 结语
doc.add_heading("三、结论与建议", level=1)
top = sorted_products[0]
doc.add_paragraph(
f"本期销售冠军为「{top[0]}」,"
f"贡献了 {top[1]['revenue'] / stats['total_revenue'] * 100:.1f}% 的销售额。"
"建议加大该产品的推广力度。"
)
doc.save(output_path)
print(f"报告已保存: {output_path}")

# === 主程序 ===
if __name__ == "__main__":
stats = read_sales_data("sales_data.xlsx")
month_str = datetime.now().strftime("%Y%m")
output = f"销售报告_{month_str}.docx"
generate_report(stats, output)
print("自动化报告生成完成!")

09 · 自动化工作流串联

在真实的工作场景中,各个自动化工具往往是串联在一起形成流水线的。一个典型的月度报告自动化流程可能是这样的:

自动化报告生成流水线
Requests
拉取API数据
→
openpyxl
写入Excel
→
python-docx
生成Word
→
schedule
定时执行
💡 系列完结寄语
恭喜你完成了全部5篇的学习!从网络请求到网页解析,从爬虫框架到运维自动化,再到办公自动化,你已经掌握了 Python 在自动化运维与爬虫领域的核心技能。接下来建议:选择一个实际项目动手实践,在实践中遇到问题再回来查阅,这才是最高效的学习方式。祝你学有所成!
📋 本篇知识回顾
openpyxl读写 Excel样式设置 Excel图表 python-docx Word模板填充 PyPDF2 PdfPlumber 自动化工作流
🎉 系列完结
恭喜你完成「Python 自动化运维与爬虫」全系列学习!
篇1:网络请求基础(Requests) ✓
篇2:网页解析(BeautifulSoup) ✓
篇3:进阶爬虫(Scrapy + Playwright) ✓
篇4:运维自动化(脚本 + 定时任务) ✓
篇5:办公自动化(Excel + Word + PDF) ✓
感谢阅读,祝你在 Python 自动化之路上越走越远!
相关阅读
想动手实操?你需要一台服务器
学编程离不开动手实操。一台入门级云服务器是你最好的练习场,数据库、对象存储、CDN、短信也都能用上,入门配置很便宜,够你把学到的东西真跑一遍。
查看腾讯云优惠查看阿里云优惠
想系统入门?配一本书
看文章学的是零散知识点,想系统入门还得有一本书打底。
Python 入门书C 与 Python 入门Web 开发书