Dalton Wright
Dalton Wright

Reputation: 13

Edit existing word doc table in python

I am trying to insert data from python into an existing word doc table. I am new to python and have found the python.docx module to be a great help in this so far but when I paste the data it is never in the correct cell of the table (or what I think is correct). I have tried to paste in the index as the data to better understand what each cell is indexed as but it is different each time (see picture 1). I do not know of a way to find the specific cells that I need to place data in. If you have any help with the python-docx module or if you think a different module would be better for my use please let me know and thank you for your time.

Indexing differences

Upvotes: 1

Views: 1771

Answers (2)

kumar
kumar

Reputation: 31

Let's assume you have 1 table in the word document.

import docx

doc = docx.Document()

print(doc.tables)  # this will give you all the table objects

so, if you wanted to add some value to the 1st row, 1st column then:

doc.tables[0].cell(0,1).text='Pavan'

Now, the text 'Pavan' will be added to the 1st row, 1st column of the table.

Upvotes: 3

AlexStox
AlexStox

Reputation: 71

  1. You can use export from Python into Excel instead and then try to paste the Excel table into the docx file. But I'm now aware of the pasting Excel table into the docx file, so if you already learned this module, maybe you know how to do it.
  2. You can find libraries for Python to export into Google Sheets or even Google Docs and then save as docx file.

Here is an example of working with Pandas and XlsxWriter

Upvotes: 0

Related Questions