问题
I'd like to update the text within a textbox without changing the formatting. In other words, I'd like to keep the original formatting of the original text while changing that text
I can update the text with the following, but the formatting is changed completely in the process.
from pptx import Presentation
prs = Presentation("C:\\original_powerpoint.pptx")
sh = prs.slides[0].shapes[0]
sh.text_frame.paragraphs[0].text = 'MY NEW TEXT'
prs.save("C:\\new_powerpoint.pptx")
How can I update the text while maintaining the original formatting?
I've also tried the following:
from pptx import Presentation
prs = Presentation("C:\\original_powerpoint.pptx")
sh = prs.slides[0].shapes[0]
p = sh.text_frame.paragraphs[0]
original_font = p.font
p.text = 'NEW TEXT'
p.font = original_font
However I get the following error:
Traceback (most recent call last):
File "C:\Codes\powerpoint_python_script.py", line 24, in <module>
p.font = original_font
AttributeError: can't set attribute
回答1:
Text frame is consists of paragraphs and paragraphs is consists of runs. So you need to set text in run.
Probably you have only one run and your code can be changed like that:
from pptx import Presentation
prs = Presentation("C:\\original_powerpoint.pptx")
sh = prs.slides[0].shapes[0]
sh.text_frame.paragraphs[0].runs[0].text = 'MY NEW TEXT'
prs.save("C:\\new_powerpoint.pptx")
Character formatting (font characteristics) are specified at the Run level. A Paragraph object contains one or more (usually more) runs. When assigning to Paragraph.text, all the runs in the paragraph are replaced with a single new run. This is why the text formatting disappears; because the runs that contained that formatting disappear.
来源:https://stackoverflow.com/questions/45247042/how-to-keep-original-text-formatting-of-text-with-python-powerpoint