打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
5分钟让你用Python作出最精美的Powerpoint

介绍

PowerPoint在大多数商业环境中被广泛使用。本文向您展示如何使用python通过使用python自动创建PowerPoint幻灯片。

5分钟让你用Python作出最精美的Powerpoint

在前面的文章里,我们讲解了很棒的python库,用于创建和更新PowerPoint文件:。该API是非常有据可查所以它是很容易使用。唯一棘手的部分是理解PowerPoint文档结构,包括各种主布局和元素。一旦理解了基础知识,自动创建自己的PowerPoint幻灯片就相对简单了。本文将介绍使用pandas读取和分析某些Excel数据,创建表格以及构建可嵌入PowerPoint文件的图形的示例。

先来看看制作的精美PPT效果吧:

精美PPT效果1

精美PPT效果2

精美PPT效果3

眼花缭乱了吧,让我们赶紧向下学习。

PowerPoint文件基础知识

Python-pptx可以创建空白的PowerPoint文件,但大多数人更愿意使用可以使用您自己的内容自定义的预定义模板。Python-pptx的API非常简单地支持这个过程,只要您了解模板的一些内容即可。

在深入研究一些代码示例之前,您需要了解两个关键组件:幻灯片布局占位符。在下面的例子中,有两个不同布局的示例以及模板的占位符,可以在其中填充内容。

在下图中,可以看到我们正在使用布局0,并且幻灯片上的索引1处有一个占位符。

在此图像中,我们使用布局1来获得完全不同的外观。

模板让工作更轻松,创建了一个简单的独立脚本,该脚本采用模板并使用各种元素对其进行标记。

这里是程序源码,不要着急,看起来很多,但是我们下面会一一讲解。

analyze_ppt.py

主要模块功能

开始讲解程序主要的功能:

def analyze_ppt(input, output): ''' Take the input file and analyze the structure. The output file contains marked up information to make it easier for generating future powerpoint templates. ''' prs = Presentation(input) # Each powerpoint file has multiple layouts # Loop through them all and see where the various elements are for index, _ in enumerate(prs.slide_layouts): slide = prs.slides.add_slide(prs.slide_layouts[index]) # Not every slide has to have a title try: title = slide.shapes.title title.text = 'Title for Layout {}'.format(index) except AttributeError: print('No Title for Layout {}'.format(index)) # Go through all the placeholders and identify them by index and type for shape in slide.placeholders: if shape.is_placeholder: phf = shape.placeholder_format # Do not overwrite the title which is just a special placeholder try: if 'Title' not in shape.text: shape.text = 'Placeholder index:{} type:{}'.format(phf.idx, shape.name) except AttributeError: print('{} has no text attribute'.format(phf.type)) print('{} {}'.format(phf.idx, shape.name)) prs.save(output)

此函数的基本流程是循环并创建源PowerPoint文件中包含的每个布局的示例。然后在每张幻灯片上,它将填充标题(如果存在)。最后,它将遍历模板中包含的所有占位符,并显示占位符的索引以及类型。

如果你想自己尝试一下:

python analyze_ppt.py simple-template.ppt simple-template-markup.ppt

创建自己的PowerPoint

下面不详细涉及pandas具体数据操作,因此在深入研究代码之前确保您对它有了解是有帮助的。让我们从程序的输入和基本shell开始:

from __future__ import print_functionfrom pptx import Presentationfrom pptx.util import Inchesimport argparseimport pandas as pdimport numpy as npfrom datetime import dateimport matplotlib.pyplot as pltimport seaborn as sns# Functions go hereif __name__ == '__main__': args = parse_args() df = pd.read_excel(args.report.name) report_data = create_pivot(df) create_chart(df, 'report-image.png') create_ppt(args.infile.name, args.outfile.name, report_data, 'report-image.png')在创建命令行args之后,将源Excel文件读入pandas DataFrame。接下来,我们使用该DataFrame作为输入来创建数据的Pivot_table摘要:def create_pivot(df, index_list=['Manager', 'Rep', 'Product'], value_list=['Price', 'Quantity']): ''' Take a DataFrame and create a pivot table Return it as a DataFrame pivot table ''' table = pd.pivot_table(df, index=index_list, values=value_list, aggfunc=[np.sum, np.mean], fill_value=0) return table下一部分分析是按帐户创建销售业绩的简单条形图:def create_chart(df, filename): ''' Create a simple bar chart saved to the filename based on the dataframe passed to the function ''' df['total'] = df['Quantity'] * df['Price'] final_plot = df.groupby('Name')['total'].sum().order().plot(kind='barh') fig = final_plot.get_figure() # Size is the same as the PowerPoint placeholder fig.set_size_inches(6, 4.5) fig.savefig(filename, bbox_inches='tight', dpi=600)这是图像的缩略图:

已经完成了图表和数据透视表。现在,将基于给定的PowerPoint模板文件将该图表嵌入到新的PowerPoint文件中。

在深入下面的讲述前,有几点需要注意。需要知道要使用的布局以及要填充内容的位置。在查看输出时,analyze_ppt.py 我们知道标题幻灯片是布局0,并且它在占位符1处具有title属性和副标题。

这是我们用来创建输出PowerPoint的函数的开头:

def create_ppt(input, output, report_data, chart): ''' Take the input powerpoint file and use it as the template for the output file. ''' prs = Presentation(input) # Use the output from analyze_ppt to understand which layouts and placeholders # to use # Create a title slide first 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 = 'Quarterly Report' subtitle.text = 'Generated on {:%m-%d-%Y}'.format(date.today())此代码基于我们的输入文件创建新的演示文稿,添加单个幻灯片并填充幻灯片上的标题和副标题。它看起来像这样:

很酷吧?

下一步是将图片嵌入幻灯片中。

从之前的分析中,我们知道想要使用的图形幻灯片是布局索引8,因此我们创建一个新幻灯片,添加标题然后将图片添加到占位符1.最后一步在占位符2处添加了一个副标题。

# Create the summary graphgraph_slide_layout = prs.slide_layouts[8]slide = prs.slides.add_slide(graph_slide_layout)title = slide.shapes.titletitle.text = 'Sales by account'placeholder = slide.placeholders[1]pic = placeholder.insert_picture(chart)subtitle = slide.placeholders[2]subtitle.text = 'Results consistent with last quarter'这是我们的杰作:

对于演示文稿的最后部分,我们将为创建一个销售绩效表。

这是效果截图:

在PowerPoint中创建表是一个好消息,也有一个坏消息。好消息是有一个API可以创建一个。坏消息是您无法使用内置API轻松将pandas DataFrame转换为表格。但是,非常幸运,有人已经为我们完成了所有艰苦的工作并创建了。这段优秀的代码采用DataFrame并将其转换为PowerPoint兼容表。我冒昧地将一部分内容包含在我的剧本中。原始版本具有更多我没有使用的功能,因此我建议您查看回购并在自己的代码中使用它。

# Create a slide for each manager

for manager in report_data.index.get_level_values(0).unique():

slide = prs.slides.add_slide(prs.slide_layouts[2])

title = slide.shapes.title

title.text = 'Report for {}'.format(manager)

top = Inches(1.5)

left = Inches(0.25)

width = Inches(9.25)

height = Inches(5.0)

# Flatten the pivot table by resetting the index

# Create a table on the slide

df_to_table(slide, report_data.xs(manager, level=0).reset_index(),

left, top, width, height)

prs.save(output)

该代码将每个业绩从pivot表中取出,并构建一个包含摘要数据的简单DataFrame。然后使用 df_to_table 将DataFrame转换为PowerPoint兼容表。

完整的代码看起来像这样:

python create_ppt.py simple-template.pptx sales-funnel.xlsx myreport.pptx

结论

阅读本文后,如果下次需要用PowerPoint中创建一堆报告时,这是一种让你免于996的好办法!赞赏请评论或转发,有更好建议请留言,我们会持续优化这篇文章。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
word、PPT、PowerPoint等技巧
3. Tensorflow Placeholders 占位符
PowerPoint 演讲放映技巧
通过python-pptx模块操作ppt文件
用Python自动生成数据分析报告
让你相见恨晚的30个PPT技巧
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服