Search code examples
pythonpowerpointcellpython-pptx

Python pptx - part of text in cell with different color


I am using pptx module to generate slide with table. I am able to change font in each cell, but what I also need is change font of specific word in text. In example "Generating random sentence as example". In this world "random" is bold.

Found similar case at text color in python-pptx module ,but that one works with "text frame" and not with cell.

Any advices/suggestions are welcomed!

Thanks


Solution

  • If you use cell where that example uses text_frame (or perhaps tf in that particular example) the rest of the code is the same. So to create "A sentence with a red word" where "red" appears in red color:

    from docx.shared import RGBColor
    
    # ---reuse existing default single paragraph in cell---
    paragraph = cell.paragraphs[0]
    
    # ---add distinct runs of text one after the other to
    # --- form paragraph contents
    paragraph.add_run("A sentence with a ")
    
    # ---colorize the run with "red" in it---
    red_run = paragraph.add_run("red")
    red_run.font.color.rgb = RGBColor(255, 0, 0)
    
    paragraph.add_run(" word.")
    

    You can find additional details in the documentation here:
    https://python-docx.readthedocs.io/en/latest/user/text.html#font-color