Skip to content
Advertisement

add content to existing docx with python-docx

I’d like to open an existing word document where I already added page numbers and just add some text and headline to it.

Here’s a basic example of how I tried to accomplish my goal

JavaScript

When I do the above mentioned with a complete fresh document everything works fine – when doing this with the already existing file it fails with the following error

JavaScript

I read the documention under http://python-docx.readthedocs.org/en/latest/user/documents.html but it seems I’m missing something – anyone got an idea?

Thanks in advance

Advertisement

Answer

python-docx can only work with styles that are already defined in the document. This error indicates that the Heading 1 paragraph style is not defined. Word starts out with no styles defined (ok, a couple like Normal, but that’s all), then it adds built-in styles to the file the first time they’re used.

Two options:

  1. Add a Heading 1 paragraph to the document by hand and then delete it. After that, the Heading 1 paragraph style will be defined in the document. Once Word adds a style it doesn’t remove it, even if all paragraphs using that style are deleted.

  2. Use python-docx to define Heading 1 yourself. See the documentation here on how to do that: http://python-docx.readthedocs.org/en/latest/user/styles-using.html#define-paragraph-formatting

This page is probably also worth a quick read to fill in some style concepts: http://python-docx.readthedocs.org/en/latest/user/styles-understanding.html

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement