lekythos
lekythos

Reputation: 123

Python docx - Is it possible to add text in middle of a word document?

I have an Excel and a Word files.

In Excel I have eg

Marc 
Henry 
Richard

In my word I have eg

TITLE
PARAPH 1    
Building has been done by : please insert name here
PARAPH 3
etc.

I managed to read Excel and to put good name for good word document. But Is there a way to insert names in the middle of my doc ?

At the end I'd like my word like

TITLE
Lorem ipsum dolor sit amet.'Lorem ipsum dolor sit amet.'Lorem ipsum dolor sit amet.'Lorem ipsum dolor sit amet.'

Building has been done by : NAME ADDED IN WORD FROM A PYTHON VARIABLE HERE

Lorem ipsum dolor sit amet.'Lorem ipsum dolor sit amet.'Lorem ipsum dolor sit amet.'

Many thanks in advance

Upvotes: 1

Views: 5599

Answers (1)

linqo
linqo

Reputation: 647

For the word documents, this sounds like a task that could be done well with the python-docx library. There's a helpful tutorial here.

The first step is to either create a Document() or open one. If you want to open an existing one, just pass that as an argument like this: Document('filename.docx'). More on working with documents here.

Then you can add a paragraph to that document using the add_paragraph() method on your Document. Pass as an argument to that method with the text you want to insert.

The python-docx documentation is extensive, and has some more good examples.

As for Excel, you'll find similar functionality in openpyxl, similarly well documented. Here's a quick tutorial on how to write Excel files (scroll down to "Creating and Saving Excel Documents").

Upvotes: 1

Related Questions