python 操作ppt
阿新 • • 發佈:2021-01-11
轉自其他部落格 實測可用
# 載入庫 import os import pandas as pd from pptx import Presentation from pptx.util import Cm, Pt from pptx.enum.text import PP_ALIGN from pptx.dml.color import RGBColor # 設定路徑 work_path = r'D:\pythonCode\ppt_wirte' os.chdir(work_path) # 定義數 square_target = [20000, 1000, 1000000, 300] square_achivement = [19000, 888, 888888, 289] month_target = [20000, 1000, 100000, 120] month_achivement = [18000, 888, 888888, 118] df = pd.DataFrame(data={'1 季度指標': square_target, '1 季度完成': square_achivement, '1 季度完成率': None, '3 月份指標': month_target, '3 月份完成': month_achivement, '3 月份完成率': None }, index = ['運營車輛(輛)', '運營網點(個)', '會員(個)', '淨收入(萬元)'] ) # 計算指標完成率,將轉換為百分數 df['1 季度完成率'] = (df['1 季度完成'] / df['1 季度指標']).apply(lambda x: format(x, '.1%')) df['3 月份完成率'] = (df['3 月份完成'] / df['3 月份指標']).apply(lambda x: format(x, '.1%')) # 例項化 ppt 文件物件 prs = Presentation() # 插入幻燈片 title_only_slide = prs.slide_layouts[5] slide_1 = prs.slides.add_slide(title_only_slide) shapes = slide_1.shapes shapes.title.text = '目標達成情況' # 預設表格總體佈局引數 rows = 5 columns = 9 left = Cm(1.5) top = Cm(4.5) width = Cm(1) height = Cm(1) # 新增表格 table = shapes.add_table(rows=rows, cols=columns, left=left, top=top, width=width, height=height ) table = table.table # 調整行高、列寬 for i in range(rows): table.rows[i].height = Cm(1) for i in range(columns): if i in (1, 5): continue table.columns[i].width = Cm(3) # 寫入表頭 header = df.columns for i, h in enumerate(header): if i >= 3: # 第六列為空白 i += 1 a = i + 2 cell = table.cell(0, a) # tf = cell.text_frame para = tf.add_paragraph() para.text = h para.font.size = Pt(13) para.alignment = PP_ALIGN.CENTER # 居中 # 寫入行名稱 row_names = df.index for i, r in enumerate(row_names): r = r.replace('(', '\n(') # 強制換行 cell = table.cell(i+1, 0) tf = cell.text_frame para = tf.add_paragraph() para.text = r para.font.size = Pt(13) para.alignment = PP_ALIGN.CENTER # 居中 # 按行寫入資料 r, c = df.shape for i in range(r): for j in range(c): a = j + 2 # 讓開前兩列 if j >= 3: # 第六列為空白 a += 1 cell = table.cell(i+1, a) tf = cell.text_frame para = tf.add_paragraph() para.text = str(df.iloc[i, j]) para.alignment = PP_ALIGN.RIGHT # 右對齊 for c in (1, 5): for r in range(rows): cell = table.cell(r, c) cell.fill.solid() cell.fill.fore_color.rgb = RGBColor(255, 255, 255) # 儲存 ppt prs.save('test_ppt_table.pptx')