how to set text in powerpoint table cell without losing font format

1.6k views Asked by At

I am writing python code to modify an existing powerpoint document using python-pptx. I can usually set text while preserving formatting, by setting text in the run:

shape.text_frame.paragraphs[0].runs[0].text = 'mytext'

However, in the tables I am modifying, the cells have no runs. They have a paragraph[0] and it contains a font object with no information (font.name, font.size, are blank). I don't know where the table font information is stored but it must have some since the table works in powerpoint. If I add a run to the paragraph and set its text, the text is not the same size as if I do this manually in the powerpoint UI. How do I set the text in a table cell while keeping the font information from the original table?

# this does not preserve table cell formatting...
table = shape.table
cell = table.rows[0].cells[0]
run = cell.text_frame.paragraphs[0].add_run()
run.text = 'mytext'
2

There are 2 answers

0
scanny On

Text formatting in PowerPoint is governed by a style hierarchy.

Formatting (such as font size or italic) applied directly to a run has first priority. From there it goes roughly paragraph default, table style (when inside a table), inherited from layout (placeholder only), inherited from master (placeholder only), and document/theme default. This varies a bit depending on location, e.g. inside a table or not, and I haven't found a clear statement of the exact rules, but this may give you an idea.

So to answer your question you'll need to learn where the formatting in your original table is coming from.

My guess would be directly applied formatting, as this is what is most readily available to an end-user. Also, you say your new runs have no directly applied formatting, which means they must be inheriting theirs from somewhere.

In that case the solution would be to discover what it is in the original runs and set it the same on the new runs. Alternatively you could change all of them to inherit from the theme/presentation defaults.

0
Giovanni On

working around the sape problem i found this solution (don't ask my why it works but it does, i just find out via trial-and-error approach):

for shape in slide.shapes:
print(shape.name)
print(shape.shape_type)
if (shape.name == str(2)) and ('TABLE' in str(shape.shape_type)):
    table = shape.table
    cell = table.cell(0, 1)
    text_frame = cell.text_frame
    for paragraph in text_frame.paragraphs:
        for run in paragraph.runs:
            run.text = run.text = 'test'