在自动化办公与数据报告生成的场景中,Python的python-docx
库以其简洁的API设计和强大的功能,成为处理Word文档的利器。无论是创建结构化文档、批量生成报告,还是处理复杂表格与图片,该库都能提供高效的解决方案。本文将系统讲解python-docx
的核心用法与高级技巧,助您快速掌握这一文档自动化神器。
pip install python-docx
# 推荐同时安装依赖库(用于图片处理)
pip install lxml pillow
pip install python-docx -i https://pypi.tuna.tsinghua.edu.cn/simple
from docx import Document
print(Document.__version__) # 输出版本号验证安装
from docx import Document
# 创建空白文档
doc = Document()
# 添加内容
doc.add_heading('自动化报告', level=0) # 主标题
doc.add_paragraph('生成时间:', style='ListBullet')
doc.add_paragraph('2025年7月9日')
# 保存文档
doc.save('./report.docx')
# 添加多级标题
doc.add_heading('第一章 概述', level=1)
doc.add_heading('1.1 背景', level=2)
# 添加带样式的段落
p = doc.add_paragraph('重点内容:')
p.add_run('数据可视化').bold = True
p.add_run('是核心需求').italic = True
run = doc.add_paragraph().add_run('关键指标')
run.font.size = Pt(16) # 字号
run.font.color.rgb = RGBColor(255, 0, 0) # 红色
run.underline = True # 下划线
paragraph = doc.add_paragraph('此段落居中显示')
paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
style = doc.styles.add_style('CustomStyle', WD_STYLE_TYPE.PARAGRAPH)
style.font.name = '微软雅黑'
style.paragraph_format.space_after = Pt(6) # 段后距
# 应用样式
doc.add_paragraph('自定义样式段落', style='CustomStyle')
# 创建3行4列表格
table = doc.add_table(rows=3, cols=4)
table.style = 'Light Shading' # 应用内置样式
# 填充表头
hdr_cells = table.rows[0].cells
hdr_cells[0].text = '姓名'
hdr_cells[1].text = '年龄'
hdr_cells[2].text = '部门'
hdr_cells[3].text = '入职日期'
# 填充数据行
row_cells = table.add_row().cells
row_cells[0].text = '张三'
row_cells[1].text = '28'
row_cells[2].text = '技术部'
row_cells[3].text = '2020-01-15'
# 合并单元格
cells = [table.cell(i, j) for i in range(2) for j in range(2)]
cells[0].merge(cells[3]) # 合并左上角2x2区域
merged_cell = cells[0]
merged_cell.text = "合并单元格示例"
# 设置单元格背景
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
shading = OxmlElement('w:shading')
shading.set(qn('w:val'), 'clear')
shading.set(qn('w:color'), 'auto')
shading.set(qn('w:fill'), 'CCCCCC') # 灰色背景
cell._tc.append(shading)
doc.add_picture('./chart.png', width=Inches(6), height=Inches(3))
from docx.shapes.graph import GraphicData
from docx.oxml.ns import qn
# 添加矩形
doc.add_paragraph().add_run().add_picture(
GraphicData(
type='rect',
x=0, y=0,
cx=Inches(2), cy=Inches(1),
fill='blue'
)
)
def add_hyperlink(paragraph, url, text):
part = paragraph.part
r_id = part.relate_to(url, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", True)
hyperlink = OxmlElement('w:hyperlink')
hyperlink.set(qn('r:id'), r_id)
run = OxmlElement('w:r')
r_text = OxmlElement('w:t')
r_text.text = text
run.append(r_text)
hyperlink.append(run)
paragraph._p.append(hyperlink)
p = doc.add_paragraph()
add_hyperlink(p, 'https://www.python.org', '访问Python官网')
section = doc.sections[0]
header = section.header
p = header.paragraphs[0]
p.text = "内部报告 - 请勿外传"
footer = section.footer
p = footer.paragraphs[0]
p.text = "第 {PAGE} 页 共 {NUMPAGES} 页".format(PAGE='PAGE', NUMPAGES='NUMPAGES')
# 使用虚拟环境
python -m venv myenv
source myenv/bin/activate # Linux/Mac
./myenv/Scripts/activate # Windows
pip install python-docx
try:
doc = Document('legacy.doc') # 旧版.doc格式不支持
except ValueError as e:
print("错误:仅支持.docx格式")
doc = Document() # 创建新文档
# 查看可用样式
for style in doc.styles:
print(f"样式名:{style.name}, 类型:{style.type}")
# 强制应用内置样式
p = doc.add_paragraph('正文内容', style='Normal')
# 确保使用绝对路径或正确相对路径
import os
img_path = os.path.abspath('./data/image.jpg')
doc.add_picture(img_path, width=Inches(4))
from concurrent.futures import ThreadPoolExecutor
def generate_report(data):
doc = Document()
# 填充数据...
doc.save(f"{data['id']}.docx")
with ThreadPoolExecutor(max_workers=4) as executor:
executor.map(generate_report, data_list)
# 预定义模板
template = Document('template.docx')
# 填充动态内容
for placeholder in template.paragraphs:
if '{{title}}' in placeholder.text:
placeholder.text = placeholder.text.replace('{{title}}', '季度报告')
# 显式关闭文档(长循环中)
docs = []
for _ in range(100):
doc = Document()
# 操作文档...
docs.append(doc)
doc.close() # 显式关闭
python-docx
通过其直观的API和全面的功能覆盖,已成为Python处理Word文档的标准库。从基础的内容创建到高级的样式定制,再到与数据分析流程的整合,该库都能提供高效的解决方案。未来可期待在以下方向的发展:
建议开发者结合pandas
进行结构化数据处理,或与matplotlib
协作生成数据图表,构建完整的自动化报告生成工作流。