关于 pptx
这项技能介绍如何使用 Python 的 `python-pptx` 库创建和编辑 PowerPoint 演示文稿,涵盖幻灯片、图片、表格、图表及现有文件的读取。
主要功能
- 01创建演示文稿和幻灯片
- 02添加图片、表格和图表
- 03读取现有演示文稿中的文本
- 04使用 Inches() 和 Pt() 设置尺寸
适用场景
- 01用 Python 制作演示文稿
- 02向幻灯片添加表格或图表
- 03检查现有文件中的文本
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ moizibnyousaf/ ai-agent-skills --skill pptx安装后在 Claude Code 中输入/pptx确认已加载。
详细介绍
PowerPoint 处理
创建演示文稿(Python)
from pptx import Presentation
from pptx.util import Inches, Pt
prs = Presentation()
# Add title slide
title_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_slide_layout)
title = slide.shapes.title
subtitle = slide.placeholders[1]
title.text = "Hello, World!"
subtitle.text = "python-pptx demo"
# Add content slide
bullet_slide_layout = prs.slide_layouts[1]
slide = prs.slides.add_slide(bullet_slide_layout)
shapes = slide.shapes
title_shape = shapes.title
body_shape = shapes.placeholders[1]
title_shape.text = "Key Points"
tf = body_shape.text_frame
tf.text = "First bullet point"
p = tf.add_paragraph()
p.text = "Second bullet point"
p.level = 1
prs.save('presentation.pptx')
添加图片
from pptx.util import Inches
blank_layout = prs.slide_layouts[6]
slide = prs.slides.add_slide(blank_layout)
left = Inches(1)
top = Inches(1)
width = Inches(5)
slide.shapes.add_picture('image.png', left, top, width=width)
添加表格
rows, cols = 3, 4
left = Inches(1)
top = Inches(2)
width = Inches(6)
height = Inches(1.5)
table = slide.shapes.add_table(rows, cols, left, top, width, height).table
# Set column widths
table.columns[0].width = Inches(2)
# Add content
table.cell(0, 0).text = "Header 1"
table.cell(1, 0).text = "Data 1"
添加图表
from pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE
chart_data = CategoryChartData()
chart_data.categories = ['East', 'West', 'Midwest']
chart_data.add_series('Sales', (19.2, 21.4, 16.7))
x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)
slide.shapes.add_chart(
XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data
)
编辑现有演示文稿
prs = Presentation('existing.pptx')
# Access slides
for slide in prs.slides:
for shape in slide.shapes:
if shape.has_text_frame:
print(shape.text_frame.text)
# Modify text
slide = prs.slides[0]
slide.shapes.title.text = "New Title"
prs.save('modified.pptx')
最佳实践
- 使用幻灯片版式保持一致
- 尽量精简文本,多用视觉元素
- 使用 Inches() 或 Pt() 设置尺寸
- 创建过程中经常保存
评论
支持 Markdown