Pregunta

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.

¿Fue útil?

Solución

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?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top