Python对ppt进行文本替换、插入图片、生成表格

目录

  • [1. 安装pptx](#1. 安装pptx)
  • [2. 文本替换和插入图片](#2. 文本替换和插入图片)
  • [3. 生成表格](#3. 生成表格)

1. 安装pptx

python 复制代码
pip install python-pptx

2. 文本替换和插入图片

  • 文本通过占位符例如{``{$xxx}}进行标记,然后进行替换;图片通过ppt中的图形和图片中的占位符进行标记
  • ppt如下
  • 具体实现
python 复制代码
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE

# 加载已有的PPT文件
prs = Presentation('ppt.pptx')
# 图片地址
new_image_path = 'python.png'
# 遍历每一张幻灯片
for slide in prs.slides:
    # 遍历幻灯片中的每一个形状
    for shape in slide.shapes:
        # 检查shape是不是文本框
        if shape.has_text_frame:
            if "{{$keyValue_text}}" in shape.text:
                # 替换文本
                shape.text = shape.text.replace("{{$keyValue_text}}", "文本替换后的内容")
        # 检查shape是不是表格
        if shape.has_table:
            for row in shape.table.rows:
                for cell in row.cells:
                    if "{{$keyValue_table}}" in cell.text:
                        cell.text = cell.text.replace('{{$keyValue_table}}', '表格替换后的内容')
        # 检查shape是不是一个图形(MSO_SHAPE_TYPE中还包含TABLE、TEXT_BOX)
        if shape.shape_type == MSO_SHAPE_TYPE.AUTO_SHAPE:
            if '{{$image}}' in shape.text:
                # 删除旧的图片占位符
                slide.shapes._spTree.remove(shape.element)
                # 在相同位置添加新图片{{$image}},同时设置图片尺寸
                left = shape.left
                top = shape.top
                width = shape.width
                height = shape.height
                slide.shapes.add_picture(new_image_path, left, top, width, height)

# 保存修改后的PPT文件
prs.save('new_ppt.pptx')
  • 执行后的效果

3. 生成表格

  • 定义一个表格,并设置表格的名称{``{$table}},表格只包含表头,根据提供的数据动态追加行并填充数据
  • 点击选择窗格,选择ppt中的表格,设置表格名称{``{$table}}
  • 具体实现
python 复制代码
from pptx import Presentation
from copy import deepcopy


# 找出表格
def find_table_by_identifier(slide, identifier):
    for shape in slide.shapes:
        if shape.has_table and shape.name == identifier:
            return shape.table
    return None


# 增加表格行
def add_row_to_table(table):
    # 复制最后一行
    new_row = deepcopy(table._tbl.tr_lst[-1])
    # 添加新行到表格
    table._tbl.append(new_row)


# 添加数据
def add_data_to_table(table, data):
    # 计算数据有多少条,增加相应数量的表格行
    rows_to_add = len(data)
    # 动态增加行
    for _ in range(rows_to_add):
        add_row_to_table(table)
    # 填充数据
    for i, row_data in enumerate(data):
        for j, cell_content in enumerate(row_data):
            cell_text = str(cell_content)
            table.cell(i + 1, j).text = cell_text


# 示例数据
data = [
    ["张三", 28, "北京"],
    ["李四", 22, "上海"],
    ["王五", 35, "广州"]
]

# 使用函数
ppt_path = 'table.pptx'
save_path = 'new_table.pptx'
prs = Presentation(ppt_path)

# 遍历每一张幻灯片寻找名称为{{$table}}的表格
for slide in prs.slides:
    table = find_table_by_identifier(slide, "{{$table}}")
    if table is not None:
        add_data_to_table(table, data)

prs.save(save_path)
  • 执行后的效果
相关推荐
名字还没想好☜23 分钟前
Python concurrent.futures 实战:用 ThreadPoolExecutor 并发处理 + as_completed 收结果
数据库·python·php·并发
爱码小白30 分钟前
importlib模块
开发语言·前端·python
axinawang1 小时前
第25课 for循环的应用
python
逻极1 小时前
FastAPI 实战:从入门到自动化文档,如何把API开发效率提升200%
python·api·fastapi·swagger·异步
半兽先生2 小时前
大模型技术开发与应用——5.大模型Agent开发(CrewAI)
大数据·人工智能·python·机器学习·ai
眼泪划过的星空2 小时前
快速了解LangGraph:构建智能Agent工作流的核心框架
人工智能·python·langchain
IsSh9nj6q2 小时前
Python全栈应用搭建神器magic-dash .新版本介绍
开发语言·python·dash
Cachel wood3 小时前
hands-on-modern-rl:动手学强化学习策略梯度reinforce
开发语言·python
蓝斯4973 小时前
一碰即传,重构跨设备文件分享体验
开发语言·python·重构
寒水馨3 小时前
macOS下载、安装uv-0.12.0(附安装包uv-aarch64-apple-darwin.tar.gz)
python·macos·rust·项目管理·包管理器·astral·pip替代