简体   繁体   中英

How to apply a style to a paragraph with python-docx?

I am trying to apply a style to a paragraph in a document using the python-docx module. I can write new text, but I cannot apply a different style to a previously-written paragraph.

Here is an example:

x = docx.Document('Sample.docx')

x
Out[81]: <docx.api.Document at 0x121cebed0>

x.paragraphs[2].style
Out[82]: 'Normal'

x.paragraphs[2].style = 'Title'

x.paragraphs[2].style
Out[84]: 'Normal'

I cannot tell from the documentation whether this should work or not. It seems to indicate that paragraph style is writable, but there is no example of this use case in the documentation.

Please let me know whether this is my problem, or if the functionality is not implemented yet.

These calls are supported. I would have to have a closer look at Sample.docx to troubleshoot.

What do you get if you take it step by step and print the results?

like:

>>> document = Document('Sample.docx')
>>> document
<docx.api.Document at 0x121cebed0>  # this looks good so far
>>> paragraphs = document.paragraphs
>>> paragraphs
???
>>> paragraph = paragraphs[2]
>>> paragraph
???
>>> paragraph.style = 'Title'
>>> paragraph.style
???

Also, getting the style name right is sometimes a trick. I don't see how that would cause the behavior you're seeing, but might be worth looking into. Are you sure you have the style 'Title' available in Sample.docx?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM