python-pptx 實踐 5:添加表格、表格填充顏色、寫入數據


1、代碼

# 加載庫
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'E:\pyspace\tmp\pptx' 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.pptx')

效果:

 

參考文章:

https://www.jianshu.com/p/39ed36e8912a


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM