使用 python-pptx 库将 Python 转换为 PPTX

问题描述 投票:0回答:2

我正在尝试使用 python 更新 ppt。我有以下一组代码,需要帮助来解决以下问题。

  1. 表中的值应该是带有逗号分隔的整数。
  2. 列应该自动调整,因为有时数字太大并且会溢出到下一行,这不能解决自动化的目的。
  3. 图表和表格重叠,有没有办法动态调整它们,使得无论表格中有多少行,图表总是在表格下方并且不重叠。
from pptx import Presentation
from pptx.util import Inches
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
table = slide.shapes.add_table(6, 6, left, top, width, height).table

# Set column widths
table.columns[0].width = Inches(2)
table.columns[1].width = Inches(1.5)
table.columns[2].width = Inches(1.5)
table.columns[3].width = Inches(1.5)
table.columns[4].width = Inches(1.5)
table.columns[5].width = Inches(1.5)

# 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):
    for j, value in enumerate(row[1:], start=1):
        table.cell(i, j).text = f'{value:.5f}'

# Plot the graph
fig, ax = plt.subplots()
df.plot(ax=ax)
plt.xlabel('X Label')
plt.ylabel('Y Label')
plt.title('Graph Title')

# Save the plot to a file
plt.savefig('graph.png')

# Add the graph to the slide
left = Inches(1)
top = Inches(5)
pic = slide.shapes.add_picture('graph.png', left, top, width=Inches(8), height=Inches(3))

# Save the presentation
prs.save(path)

# Close the plot
plt.close()

python python-pptx presentation
2个回答
0
投票

我曾经在一所大学工作过。在那里,我编写了一个Python程序来生成教授评估统计结果的PDF。结果是具有固定行数和可变列数(从 4 到 20 列)的表格。

为报告的所有可能变化生成美观的报告即使不是不可能,也是很困难的。因此,我创建了一个 OpenOffice.org Flat XML ODF 文本文档 (.fodt) 作为每个变体的模板。然后,我根据列数选择适当的模板文件并填充它,并以编程方式使用 OpenOffice 将其转换为 PDF。

结果非常好。因此,我在这里建议使用 LibreOffice Flat XML ODF 演示文稿 (.fodp)

类似的解决方案

如果您不想执行此方法,则必须根据表格的行数和列数设置表格的字体大小。您必须将表格单元格的边距设置为 0 并使用最小行高度。


0
投票

我建议使用表格对象的

top
height
属性来计算表格的底部。然后将图形位置设置为
top + height + pad
,其中
pad
是表格和图形之间所需的填充。

您可能会遇到图像太大而无法放入幻灯片的情况。在这种情况下,您可以根据桌子底部和幻灯片底部之间的剩余空间缩放图像。

© www.soinside.com 2019 - 2024. All rights reserved.