How do I apply both bold and italics in python-docx?

依然范特西╮ 提交于 2020-05-27 09:32:08

问题


I'm working on making a dictionary. I'm using python-docx to put it into MS Word. I can easily make it bold, or italics, but can't seem to figure out how to do both. Here's the basics:

import docx

word = 'Dictionary'

doc = docx.Document()
p = doc.add_paragraph()
p.add_run(word).bold = True

doc.save('test.docx')

I have tried p.add_run(word).bold.italic = True, but receive a 'NoneType' error, which I understand.

I have also tried p.bold = True and p.italic = True before and after the add_run, but lose formatting all together.

Word's find/replace is a simple solution, but I'd prefer to do it in the code if I can.


回答1:


The add_run method will return a new instance of Run each time it is called. You need create a single instance and then apply italic and bold

import docx

word = 'Dictionary'

doc = docx.Document()
p = doc.add_paragraph()

runner = p.add_run(word)
runner.bold = True
runner.italic = True

doc.save('test.docx')


来源:https://stackoverflow.com/questions/39709527/how-do-i-apply-both-bold-and-italics-in-python-docx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!