5分鐘讓你用Python作出最精美的Powerpoint

PowerPoint Python 腳本語言 Excel python小白社區 2019-06-17

介紹

PowerPoint在大多數商業環境中被廣泛使用。本文向您展示如何使用python通過使用python自動創建PowerPoint幻燈片。

5分鐘讓你用Python作出最精美的Powerpoint

5分鐘讓你用Python作出最精美的Powerpoint

在前面的文章裡,我們講解了很棒的python庫,用於創建和更新PowerPoint文件:。該API是非常有據可查所以它是很容易使用。唯一棘手的部分是理解PowerPoint文檔結構,包括各種主佈局和元素。一旦理解了基礎知識,自動創建自己的PowerPoint幻燈片就相對簡單了。本文將介紹使用pandas讀取和分析某些Excel數據,創建表格以及構建可嵌入PowerPoint文件的圖形的示例。

先來看看製作的精美PPT效果吧:

5分鐘讓你用Python作出最精美的Powerpoint

精美PPT效果1

5分鐘讓你用Python作出最精美的Powerpoint

精美PPT效果2

5分鐘讓你用Python作出最精美的Powerpoint

精美PPT效果3

眼花繚亂了吧,讓我們趕緊向下學習。

PowerPoint文件基礎知識

Python-pptx可以創建空白的PowerPoint文件,但大多數人更願意使用可以使用您自己的內容自定義的預定義模板。Python-pptx的API非常簡單地支持這個過程,只要您瞭解模板的一些內容即可。

在深入研究一些代碼示例之前,您需要了解兩個關鍵組件:幻燈片佈局佔位符。在下面的例子中,有兩個不同佈局的示例以及模板的佔位符,可以在其中填充內容。

在下圖中,可以看到我們正在使用佈局0,並且幻燈片上的索引1處有一個佔位符。

5分鐘讓你用Python作出最精美的Powerpoint

在此圖像中,我們使用佈局1來獲得完全不同的外觀。

5分鐘讓你用Python作出最精美的Powerpoint

模板讓工作更輕鬆,創建了一個簡單的獨立腳本,該腳本採用模板並使用各種元素對其進行標記。

這裡是程序源碼,不要著急,看起來很多,但是我們下面會一一講解。

5分鐘讓你用Python作出最精美的Powerpoint

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_function
from pptx import Presentation
from pptx.util import Inches
import argparse
import pandas as pd
import numpy as np
from datetime import date
import matplotlib.pyplot as plt
import seaborn as sns
# Functions go here
if __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)
這是圖像的縮略圖:
5分鐘讓你用Python作出最精美的Powerpoint

已經完成了圖表和數據透視表。現在,將基於給定的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())
此代碼基於我們的輸入文件創建新的演示文稿,添加單個幻燈片並填充幻燈片上的標題和副標題。它看起來像這樣:
5分鐘讓你用Python作出最精美的Powerpoint

很酷吧?

下一步是將圖片嵌入幻燈片中。

從之前的分析中,我們知道想要使用的圖形幻燈片是佈局索引8,因此我們創建一個新幻燈片,添加標題然後將圖片添加到佔位符1.最後一步在佔位符2處添加了一個副標題。

# Create the summary graph
graph_slide_layout = prs.slide_layouts[8]
slide = prs.slides.add_slide(graph_slide_layout)
title = slide.shapes.title
title.text = "Sales by account"
placeholder = slide.placeholders[1]
pic = placeholder.insert_picture(chart)
subtitle = slide.placeholders[2]
subtitle.text = "Results consistent with last quarter"
這是我們的傑作:
5分鐘讓你用Python作出最精美的Powerpoint

對於演示文稿的最後部分,我們將為創建一個銷售績效表。

這是效果截圖:

5分鐘讓你用Python作出最精美的Powerpoint

在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的好辦法!讚賞請評論或轉發,有更好建議請留言,我們會持續優化這篇文章。

相關推薦

推薦中...