运维-打开Word文档并插入图片

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即可完成相关功能。
模板格式为
在这里插入图片描述
生成后的文件为
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

angushine

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值