python-docx是一个用于读取、创建和更新 Microsoft Word 2007+ (.docx) 文件的 Python 库。
大家好,今天为大家分享一个超厉害的 Python 库 —— python-docx。
Github地址:https://github.com/python-openxml/python-docx
在日常工作中,处理和生成 Word 文档是一个常见需求。Python 提供了一个强大的库 python-docx,使得操作 Word 文档变得简单和高效。python-docx 可帮助我们创建、修改和读取 Word 文档,适用于自动化报告生成、批量文档处理等应用场景。本文将详细介绍该库的安装、主要特性、基本和高级功能,以及实际应用场景,帮助你全面掌握 python-docx 的使用。
安装
要使用 python-docx,首先需要安装它。
使用 pip 安装
pip install python-docx
确认安装
安装完成后,可以通过以下命令确认安装是否成功:
python -c "import docx; print(docx.__version__)"
特性
- 创建和修改文档:可以从头创建一个新的 Word 文档或修改现有文档。
- 支持多种格式:支持文本的字体、大小、颜色、对齐等设置。
- 图像和表格:支持插入和操作图像、表格。
- 段落和标题:支持添加段落、标题,结构化文档内容。
- 灵活扩展:通过 API 灵活自定义,满足特定需求。
基本功能
创建和保存文档
from docx import Document
# 创建一个新的文档
doc = Document()
# 添加标题和段落
doc.add_heading('Document Title', level=1)
doc.add_paragraph('This is a paragraph in the document.')
# 保存文档
doc.save('example.docx')
打开和修改文档
from docx import Document
# 打开现有文档
doc = Document('existing.docx')
# 添加新的段落
doc.add_paragraph('This is a new paragraph.')
# 保存修改后的文档
doc.save('modified.docx')
设置文本格式
from docx import Document
from docx.shared import Pt, RGBColor
doc = Document()
run = doc.add_paragraph().add_run('Formatted Text')
# 设置字体、大小和颜色
run.font.name = 'Arial'
run.font.size = Pt(12)
run.font.color.rgb = RGBColor(255, 0, 0)
doc.save('formatted.docx')
插入图片
from docx import Document
from docx.shared import Inches
doc = Document()
doc.add_heading('Document with Image', level=1)
# 插入图片
doc.add_picture('image.png', width=Inches(4))
doc.save('document_with_image.docx')
添加表格
from docx import Document
doc = Document()
table = doc.add_table(rows=2, cols=2)
# 填充表格数据
table.cell(0, 0).text = 'Header 1'
table.cell(0, 1).text = 'Header 2'
table.cell(1, 0).text = 'Cell 1'
table.cell(1, 1).text = 'Cell 2'
doc.save('table.docx')
高级功能
设置段落样式
from docx import Document
doc = Document()
paragraph = doc.add_paragraph('Styled Paragraph')
paragraph.style = 'Title' # 使用内置样式
doc.save('styled_paragraph.docx')
添加页眉和页脚
from docx import Document
doc = Document()
# 添加页眉
header = doc.sections[0].header
header.paragraphs[0].text = 'This is the header'
# 添加页脚
footer = doc.sections[0].footer
footer.paragraphs[0].text = 'This is the footer'
doc.save('header_footer.docx')
设置段落格式
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc = Document()
paragraph = doc.add_paragraph('Aligned Paragraph')
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER # 居中对齐
# 设置段落间距和缩进
paragraph_format = paragraph.paragraph_format
paragraph_format.space_before = Pt(12)
paragraph_format.space_after = Pt(12)
paragraph_format.left_indent = Pt(24)
doc.save('formatted_paragraph.docx')
操作复杂表格
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc = Document()
table = doc.add_table(rows=3, cols=3)
# 合并单元格
cell = table.cell(0, 0)
cell.merge(table.cell(0, 2))
# 设置单元格样式
cell.text = 'Merged Cell'
cell.paragraphs[0].runs[0].font.bold = True
cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
doc.save('complex_table.docx')
实际应用场景
自动化报告生成
在数据分析或业务管理中,通过 python-docx 自动生成和更新 Word 报告,节省人工操作时间。
from docx import Document
import pandas as pd
# 假设有一个数据分析结果 DataFrame
data = {
'Month': ['January', 'February', 'March'],
'Revenue': [1000, 1500, 2000]
}
df = pd.DataFrame(data)
# 创建报告文档
doc = Document()
doc.add_heading('Monthly Revenue Report', level=1)
# 添加表格并填充数据
table = doc.add_table(rows=1, cols=len(df.columns))
hdr_cells = table.rows[0].cells
for i, column_name in enumerate(df.columns):
hdr_cells[i].text = column_name
for index, row in df.iterrows():
row_cells = table.add_row().cells
for i, value in enumerate(row):
row_cells[i].text = str(value)
# 保存报告
doc.save('revenue_report.docx')
批量文档处理
import os
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
# 批量处理文档目录中的所有 Word 文档
directory = 'documents'
for filename in os.listdir(directory):
if filename.endswith('.docx'):
doc_path = os.path.join(directory, filename)
doc = Document(doc_path)
# 添加公司标识到页眉
header = doc.sections[0].header
header.paragraphs[0].text = 'Company Name'
# 统一文档格式
for paragraph in doc.paragraphs:
paragraph.style = 'Normal'
paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
# 保存修改后的文档
doc.save(doc_path)
动态合同生成
from docx import Document
def generate_contract(client_name, project_name, contract_date):
doc = Document('contract_template.docx')
# 填写合同信息
for paragraph in doc.paragraphs:
if '{{client_name}}' in paragraph.text:
paragraph.text = paragraph.text.replace('{{client_name}}', client_name)
if '{{project_name}}' in paragraph.text:
paragraph.text = paragraph.text.replace('{{project_name}}', project_name)
if '{{contract_date}}' in paragraph.text:
paragraph.text = paragraph.text.replace('{{contract_date}}', contract_date)
# 保存合同
doc.save(f'{client_name}_contract.docx')
# 使用动态合同生成函数
generate_contract('John Doe', 'Website Development', '2023-01-01')
总结
python-docx 是一个功能强大且易用的工具,能够帮助开发者在各种应用场景中高效操作和生成 Word 文档。无论是自动化报告生成、批量文档处理,还是动态合同生成,python-docx 都提供了强大的功能和灵活性。希望本文能帮助大家全面掌握 python-docx 库的使用,在实际项目中充分发挥其优势。