转自其他博客 实测可用


# 加载库
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')

精简版

from pptx import Presentation
from pptx.util import Inches, Pt

# 创建新的ppt文档
#prs = Presentation()
# 打开一个ppt文档
prs = Presentation('test.pptx')

#页面
title_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_slide_layout)

#容器
shapes = slide.shapes
shapes.text = 'hello world'

#添加文本
left = top = width = height = Inches(1)
txBox = slide.shapes.add_textbox(left, top, width, height)
tf = txBox.text_frame
tf.text = "first paragraph"
p = tf.add_paragraph()
p.text = "second paragraph"

#添加表格
rows = cols = 2
left = top = Inches(2.0)
width = Inches(6.0)
height = Inches(0.8)
table = shapes.add_table(rows, cols, left, top, width, height).table
table.columns[0].width = Inches(2.0)
table.columns[1].width = Inches(4.0)
# write column headings
table.cell(0, 0).text = 'Foo'
table.cell(0, 1).text = 'Bar'

# 保存ppt文档
prs.save('test.pptx')