1、需求背景
接前面访问系统自动截图的需求,需要将截到的图片插入到运维报告中指定位置,具体需求是:打开一个运维报告模板,文件为Word文档,需要将文档中特定文本格式为#P1#,#P2#等替换为指定的图片,这些特定文本可能在段落中,也可能在表格中,还能在多层嵌套表格中。
2、安装插件
Python使用的版本为3.12.7,需安装Word相关插件pip install python-docx
3、源代码
from docx import Document
from docx.shared import Inches
import re
import os
def process_paragraph(paragraph, placeholder_map):
"""
处理单个段落中的占位符
"""
for placeholder, (image_path, width) in placeholder_map.items():
if placeholder in paragraph.text:
# 使用正则表达式查找所有匹配项
matches = list(re.finditer(re.escape(placeholder), paragraph.text))
# 从后往前替换避免索引偏移
for match in reversed(matches):
start, end = match.span()
# 分割文本
before = paragraph.text[:start]
after = paragraph.text[end:]
# 清空段落并重建内容
paragraph.clear()
# 添加前半部分文本
if before:
paragraph.add_run(before)
# 添加图片
try:
paragraph.add_run().add_picture(image_path, width=width)
print(f"已插入图片: {os.path.basename(image_path)} -> {placeholder}")
except FileNotFoundError:
print(f"图片未找到: {image_path}")
paragraph.add_run(placeholder) # 保留占位符
continue
# 添加后半部分文本
if after:
paragraph.add_run(after)
def process_table(table, placeholder_map):
"""
递归处理表格(包括嵌套表格)
"""
for row in table.rows:
for cell in row.cells:
# 处理单元格中的段落
for paragraph in cell.paragraphs:
process_paragraph(paragraph, placeholder_map)
# 递归处理嵌套表格
for nested_table in cell.tables:
process_table(nested_table, placeholder_map)
def process_document(doc_path, placeholder_map, output_path):
"""
主处理函数
"""
doc = Document(doc_path)
# 处理所有段落
for paragraph in doc.paragraphs:
process_paragraph(paragraph, placeholder_map)
# 处理所有表格(包括嵌套表格)
for table in doc.tables:
process_table(table, placeholder_map)
# 保存文档
doc.save(output_path)
print(f"\n处理完成,已保存到: {os.path.abspath(output_path)}")
if __name__ == "__main__":
# 配置参数
doc_path = "word.docx" # 输入文档路径
output_path = "word-2.docx" # 输出文档路径
# 占位符配置(占位符: (图片路径, 宽度))
placeholder_map = {
"#P1#": ("screenshot.png", Inches(1.0)),
"#P2#": ("screenshot.png", Inches(1.0)),
"#P3#": ("screenshot.png", Inches(1.0)),
"#P4#": ("screenshot.png", Inches(1.0))
}
# 验证图片存在
missing_images = [ph for ph, (path, _) in placeholder_map.items() if not os.path.exists(path)]
if missing_images:
print("以下图片文件未找到:")
for ph in missing_images:
print(f" - {placeholder_map[ph][0]}")
exit(1)
# 执行处理
process_document(doc_path, placeholder_map, output_path)
运行
执行python word.py即可完成相关功能。
模板格式为

生成后的文件为

3630

被折叠的 条评论
为什么被折叠?



