python-读写docx文档-插入图片+修改格式

环境:
python 3.9.13,docx 1.1.0


之前写过:

python读写word文档-docx和docx2txt包使用实例-CSDN博客
https://blog.csdn.net/pxy7896/article/details/107160513

问题描述

同事有一个word模板,需要在某个位置插入带背景色的序列和几张图片。位置可以通过唯一关键字确定。

实现效果

插入的内容如下图所示:(已隐藏序列信息)
在这里插入图片描述

解决方案

使用docx包,搜索关键字,然后在关键字后插入拼接好的序列(同时设置背景色),随后逐张插入图片。

# _*_ coding:utf-8 _*_

from docx import Document
from docx.shared import Inches, Cm
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.enum.text import WD_COLOR_INDEX

def process(name, seq, in_file, out_file, imgs):
    document = Document(in_file)
    keyword = "蛋白名称"
    # 遍历,查找关键词
    for paragraph in document.paragraphs:
        if keyword in paragraph.text:
            # 计算插入位置
            pos = paragraph.text.find(keyword) + len(keyword)
            # 分割现有文本
            before_text = paragraph.text[:pos]
            after_text = paragraph.text[pos:]
            # 设置段落文本为分割后的文本
            paragraph.text = before_text
            # 插入header
            run = paragraph.add_run("\n>" + name + "\n")
            run = paragraph.add_run("氨基酸序列\n" + seq + "\n")
            # 关于背景色看下面的链接
            # https://python-docx.readthedocs.io/en/latest/dev/analysis/features/text/font-highlight-color.html?highlight=highlight
            run.font.highlight_color = WD_COLOR_INDEX.TURQUOISE
            #run = paragraph.add_run(after_text)
            # 插入图片
            run = paragraph.add_run()
            for img in imgs:
                run.add_picture(img, width=Cm(12))
            # 整段对齐
            paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
            # 跳出
            break
    document.save(out_file)

if __name__ == "__main__":
    name = "PDP1-RD-CDS"
    seq = "M***V*"
    in_file = "模板.docx"
    out_file = "输出.docx"
    imgs = ['1.png', '2.png']
    process(name, seq, in_file, out_file, imgs)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值