You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用python-pptx库实现PPT自动化的三类问题求助

解决PPT生成中的三个表格与图表布局问题

针对你提出的三个技术问题,以下是具体解决方案及修改后的完整代码:

1. 表格数值显示为带千分位逗号的整数

将数值四舍五入取整后,使用Python格式化语法"{:,}"实现千分位分隔,直接生成符合要求的字符串:

table.cell(i, j).text = "{:,}".format(int(round(value)))

2. 列宽自动适配内容

通过遍历每一列的所有单元格,近似计算文本的显示宽度(基于默认11pt Calibri字体,每个字符约占0.1英寸),将列宽设置为该列最大文本宽度加边距:

def get_text_width(text):
    return Inches(len(text) * 0.1 + 0.2)  # 字符宽度+边距

for col_idx in range(table.columns.count):
    max_width = Inches(1)  # 最小列宽限制
    for row_idx in range(table.rows.count):
        cell_text = table.cell(row_idx, col_idx).text
        current_width = get_text_width(cell_text)
        if current_width > max_width:
            max_width = current_width
    table.columns[col_idx].width = max_width

如果需要更精确的宽度计算,可安装pywin32库调用Windows API获取文本实际渲染宽度,上述近似方法适用于大多数常规场景。

3. 动态调整图表位置

创建表格时保留对应的Shape对象,通过Shape的top和height属性计算表格底部位置,将图表的top设为表格底部加固定间距,确保图表始终位于表格下方且不重叠:

# 创建表格时保存shape对象
table_shape = slide.shapes.add_table(len(df)+1, len(df.columns)+1, left, top, width, height)
table = table_shape.table

# 动态计算图表顶部位置
chart_top = table_shape.top + table_shape.height + Inches(0.2)
pic = slide.shapes.add_picture('graph.png', left, chart_top, width=Inches(8), height=Inches(3))

修改后的完整代码

from pptx import Presentation
from pptx.util import Inches, Pt
import pandas as pd
import matplotlib.pyplot as plt

path = 'C:/Users/admin/Desktop/Demo/Demo.pptx'
# Sample data
data = {
    'Column1': [1234.56789, 2345.67890, 3456.78901, 4567.89012, 5678.90123],
    'Column2': [9876.54321, 8765.43210, 7654.32109, 6543.21098, 5432.10987],
    'Column3': [3210.98765, 4321.09876, 5432.10987, 6543.21098, 7654.32109],
    'Column4': [7890.12345, 8901.23456, 9012.34567, 1234.56789, 2345.67890],
    'Column5': [4567.89012, 3456.78901, 2345.67890, 1234.56789, 9876.54321]
}

# Create a DataFrame
df = pd.DataFrame(data)

# Create a PowerPoint presentation
prs = Presentation()

# Add first slide with title
slide = prs.slides.add_slide(prs.slide_layouts[0])
title = slide.shapes.title
title.text = "Analysis"

# Add a slide for data and graph
slide = prs.slides.add_slide(prs.slide_layouts[5])  # Layout for title and content

# Add title for the slide
title_shape = slide.shapes.title
title_shape.text = "Basic Summary"

# Add a table for the data
left = Inches(1)
top = Inches(1.5)
width = Inches(8)
height = Inches(4)

# Create a table with rows and columns, save the shape object
table_shape = slide.shapes.add_table(len(df)+1, len(df.columns)+1, left, top, width, height)
table = table_shape.table

# Set column titles
table.cell(0, 0).text = '序号'
for i, col in enumerate(df.columns):
    table.cell(0, i+1).text = col

# Populate the table with data (千分位整数格式)
for i, row in enumerate(df.itertuples(), start=1):
    # 设置行号
    table.cell(i, 0).text = str(i)
    for j, value in enumerate(row[1:], start=1):
        # 四舍五入取整后添加千分位逗号
        table.cell(i, j).text = "{:,}".format(int(round(value)))

# 自动适配列宽
def get_text_width(text):
    # 近似计算:11pt Calibri每个字符约0.1英寸,加上0.2英寸边距
    return Inches(len(text) * 0.1 + 0.2)

for col_idx in range(table.columns.count):
    max_width = Inches(1)  # 最小列宽限制
    for row_idx in range(table.rows.count):
        cell_text = table.cell(row_idx, col_idx).text
        current_width = get_text_width(cell_text)
        if current_width > max_width:
            max_width = current_width
    table.columns[col_idx].width = max_width

# Plot the graph
fig, ax = plt.subplots()
df.plot(ax=ax)
plt.xlabel('X轴标签')
plt.ylabel('Y轴标签')
plt.title('图表标题')

# Save the plot to a file
plt.savefig('graph.png', bbox_inches='tight')  # 避免图表内容被裁剪

# Add the graph to the slide - 动态计算位置
chart_left = Inches(1)
chart_top = table_shape.top + table_shape.height + Inches(0.2)  # 表格底部+间距
pic = slide.shapes.add_picture('graph.png', chart_left, chart_top, width=Inches(8), height=Inches(3))

# Save the presentation
prs.save(path)

# Close the plot
plt.close()

内容的提问来源于stack exchange,提问作者Add

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 17:44:54