點擊上方 「AirPython」,選擇 「加爲星標」html
第一時間關注 Python 技術乾貨!python
1. 前言
做爲辦公自動化 PPT 系列篇的最後一篇文章,咱們將 PPT 中的高級功能及經常使用點web
文章內容將覆蓋:
算法
預設形狀 Shape編程
圖表 Chart
api讀取文字內容微信
保存全部圖片網絡
2. 預設形狀 Shape
實際上,PPT 文檔的內容區就是由各種形狀 Shape 組成,包含:圖片、文本框、視頻、表格、預設形狀app
其中,預設的普通形狀也至關豐富,能夠查看下面連接dom
使用下面的方法,能夠向幻燈片中插入一個形狀
slide.shapes.add_shape(autoshape_type_id, left, top, width, height)
參數分別是:
autoshape_type_id 形狀類型
left 左邊距
top 上邊距
width 形狀寬度
height 形狀高度
咱們以插入一個簡單的圓角矩形框爲例
2-1 插入形狀
2-2 設置形狀屬性
上面方法返回的形狀對象 ,咱們能夠進一步設置它的背景顏色及邊框屬性
好比:設置背景色爲白色;邊框顏色爲紅色,寬度爲 0.5 釐米
更多形狀能夠參考下面連接
https://python-pptx.readthedocs.io/en/latest/api/enum/MsoAutoShapeType.html
from pptx.enum.shapes import MSO_SHAPE, MSO_SHAPE_TYPEdef insert_shape(slide, left, top, width, height, autoshape_type_id=MSO_SHAPE.CHEVRON, unit=Inches):
"""
幻燈片中添加形狀
:param unit: 單位,默認爲Inches
:param autoshape_type_id: 形狀類型
:param slide:幻燈片
:param left:左邊距
:param top:上邊距
:param width:寬度
:param height:高度
:return:
"""
# 添加一個形狀
# add_shape(self, autoshape_type_id, left, top, width, height)
# 參數分別爲:形狀類型、左邊距、上邊距、寬度、高度
shape = slide.shapes.add_shape(autoshape_type_id=autoshape_type_id,
left=unit(left),
top=unit(top),
width=unit(width),
height=unit(height))
return shape
# 一、添加一個圓角矩形
rectangle = insert_shape(slide, 2, 2, 16, 8, autoshape_type_id=MSO_SHAPE.ROUNDED_RECTANGLE, unit=Cm)
# 二、設置形狀屬性
# 2.1 背景顏色
set_widget_bg(rectangle, bg_rgb_color=[255, 255, 255])
# 2.2 邊框屬性
set_widget_frame(rectangle, frame_rgb_color=[255, 0, 0],frame_width=0.5)
3. 圖表 Chart
圖表 Chart 是 PPT 中使用很頻繁的一塊內容,使用 python-pptx 能夠建立各類類型的圖表,包含:柱狀圖、餅圖、折線圖、散點圖、3D 圖等
建立圖表的方式以下:
slide.shapes.add_shape(autoshape_type_id, left, top, width, height)
參數分別是:
autoshape_type_id 圖表樣式
left 左邊距
top 上邊距
width 圖表顯示寬度
height 圖表顯示高度
3-1 建立一個折線圖
首先,建立一個圖表數據對象 ChartData
from pptx.chart.data import ChartData
slide = add_slide(self.presentation, 6)
# 建立一個圖表數據對象
chart_data = ChartData()
接着,準備圖表數據
# 數據類別(x軸數據)
chart_data.categories = [2000, 2005, 2010, 2015, 2020]
# 每年各維度的數據(3個緯度)
# 經濟
chart_data.add_series("經濟", [60, 65, 75, 90, 95])
# 環境
chart_data.add_series("環境", [95, 88, 84, 70, 54])
# 文化
chart_data.add_series("軍事",[40, 65, 80, 95, 98])
最後,指定圖表類型爲折線圖 XL_CHART_TYPE.LINE,按照圖表數據繪製圖表
若是須要繪製其餘圖表,能夠參考下面連接:
https://python-pptx.readthedocs.io/en/latest/api/enum/XlChartType.html
def insert_chart(slide, left, top, width, height, data, unit=Inches, chart_type=XL_CHART_TYPE.COLUMN_CLUSTERED):
"""
插入圖表
:param slide: 幻燈片
:param left: 左邊距
:param top: 上邊距
:param width: 寬度
:param height: 高度
:param data: 圖表數據
:param unit: 數據單位,默認爲:Inches
:param chart_type: 圖表類型,默認是:柱狀圖
:return:
"""
chart_result = slide.shapes.add_chart(chart_type=chart_type,
x=unit(left), y=unit(top),
cx=unit(width), cy=unit(height),
chart_data=data)
# 返回圖表
return chart_result.chart
# 添加圖表
chart = insert_chart(slide, 4, 5, 20, 9, chart_data, unit=Cm, chart_type=XL_CHART_TYPE.LINE)
3-2 設置圖表顯示屬性
以設置圖表圖例、圖表是否顯示平滑、設置圖表文字樣式爲例
# 設置圖表顯示屬性
# 顯示圖例
chart.has_legend = True
# 圖例是否在繪圖區以外顯示
chart.legend.include_in_layout = False
# 設置圖表是否顯示平滑
chart.series[0].smooth = True
chart.series[1].smooth = True
chart.series[2].smooth = True
# 設置圖表中文字的樣式
set_font_style(chart.font, font_size=12, font_color=[255, 0, 0])
最後生成的折線圖效果圖以下:
4. 讀取內容
PPT 文檔的內容區由各類 Shape 組成,而且 shape.has_text_frame 可用於判斷形狀內部是否包含文本框
所以,只須要遍歷全部形狀,就能夠獲取 PPT 中全部的文本內容
def read_ppt_content(presentation):
"""
讀取PPT中全部的內容
:param presentation:
:return:
"""
# 全部內容
results = []
# 遍歷全部幻燈片,獲取文本框中的值
for slide in presentation.slides:
for shape in slide.shapes:
# 判斷形狀是否包含文本框
if shape.has_text_frame:
content = get_shape_content(shape)
if content:
results.append(content)
return results
presentation = Presentation("./raw.pptx")
# 一、普通形狀內容的全部文本內容
contents = read_ppt_content(presentation)
print(contents)
可是,對於圖表 Table 單元格中的文本數據,無法利用這種方式獲取到
咱們只能過濾出形狀類型爲 TABLE 的形狀,遍歷表中全部行及單元格,獲取文本數據
def read_ppt_file_table(self):
"""
讀取PPT中的數據
:return:
"""
# 打開待讀取的ppt
presentation = Presentation("./raw.pptx")
for slide in presentation.slides:
# 遍歷素有形狀
# 形狀:有內容的形狀、無內容的形狀
for shape in slide.shapes:
# print('當前形狀名稱:', shape.shape_type)
# 只取表格中的數據,按照行讀取內容
if shape.shape_type == MSO_SHAPE_TYPE.TABLE:
# 獲取表格行(shape.table.rows)
for row in shape.table.rows:
# 某一行全部的單元格(row.cells)
for cell in row.cells:
# 單元格文本框中的內容(cell.text_frame.text)
print(cell.text_frame.text)
5. 保存圖片
有時候,咱們須要將 PPT 文檔中的全部圖片保存到本地
只須要下面 3 步便可完成
遍歷幻燈片內容區全部形狀
過濾出形狀類型爲 MSO_SHAPE_TYPE.PICTURE 的圖片形狀,獲取圖片形狀的二進制字節流
將圖片字節流寫入到文件中
def save_ppt_images(presentation, output_path):
"""
保存ppt中全部圖片
[Python批量導出PPT中的圖片素材](https://www.pythonf.cn/read/49552)
:param presentation:
:param output_path 保存目錄
:return:
"""
print('幻燈片數目:', len(presentation.slides))
# 遍歷全部幻燈片
for index_slide, slide in enumerate(presentation.slides):
# 遍歷全部形狀
for index_shape, shape in enumerate(slide.shapes):
# 形狀包含:文字形狀、圖片、普通形狀等
# 過濾出圖片形狀
if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
# 獲取圖片二進制字符流
image_data = shape.image.blob
# image/jpeg、image/png等
image_type_pre = shape.image.content_type
# 圖片後綴名
image_suffix = image_type_pre.split('/')[1]
# 建立image文件夾保存抽出圖片
if not os.path.exists(output_path):
os.makedirs(output_path)
# 圖片保存路徑
output_image_path = output_path + random_str(10) + "." + image_suffix
print(output_image_path)
# 寫入到新的文件中
with open(output_image_path, 'wb') as file:
file.write(image_data)
6. 最後
至此,Python 辦公自動化 PPT 系列篇就正式結束了!在實際項目中,若是你有遇到其餘問題,歡迎在評論區留言!
我已經將所有源碼上傳到後臺,關注公衆號,後臺回覆「 ppt 」便可得到所有源碼
若是你以爲文章還不錯,請你們 點贊、分享、留言 下,由於這將是我持續輸出更多優質文章的最強動力!
![](http://static.javashuo.com/static/loading.gif)
本文分享自微信公衆號 - AirPython(AirPython)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。