首页 > 解决方案 > 使用python为ppt中的表格单元格着色

问题描述

所以我有一个包含这样的表格的excel:

在此处输入图像描述

我想使用 Python 在 powerpoint 中获得同一张表

到目前为止完成的工作

  1. 将excel读取到python并存储在pandas df中
  2. 将 df 添加到 powerpoint

相同努力的代码:

from pd2ppt import df_to_table
import pandas as pd
from pptx import Presentation
from pptx.util import Inches

path =r"Sample PPT.pptx"
prs = Presentation(path)
title_slide_layout = prs.slide_layouts[5]
slide = prs.slides.add_slide(title_slide_layout)
title = slide.shapes.title
title.text = "Summary Table"

top = Inches(1.5)
left =Inches(0.25)
width =Inches(9.25)
height= Inches(5.0)


df_to_table(slide, df,left, top, width, height)

我只需要如何使用 Python 在此表中进行颜色格式化?

标签: pythonpython-pptx

解决方案


PowerPoint 表格中的每个单元格都有自己的fill,它可以做其他FillFormat对象可以做的所有事情::

from pptx.dml.color import RGBColor

cell = table.cell(0, 0)  # ---or whatever cell you choose---
fill = cell.fill
fill.solid()
fill.fore_color.rgb = RGBColor(0xFA, 0x00, 0x37)

此处的FillFormat文档中进一步描述了对象接口:
https ://python-pptx.readthedocs.io/en/latest/api/dml.html#fillformat-objects


推荐阅读