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