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
非学无以广才,非志无以成学。