Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to insert row at specific position with python-docx?

I'd like to insert a couple of rows in the middle of the table using python-docx. Is there any way to do it? I've tried to use a similar to inserting pictures approach but it didn't work.

If not, I'd appreciate any hint on which module is a better fit for this task. Thanks.

Here is my attempt to mimic the idea for inserting a picture. It's WRONG. 'Run' object has no attribute 'add_row'.

from docx import Document
doc = Document('your docx file')
tables = doc.tables
p = tables[1].rows[4].cells[0].add_paragraph()
r = p.add_run()
r.add_row()
doc.save('test.docx')
like image 952
T0f Avatar asked Sep 14 '17 09:09

T0f


2 Answers

The short answer is No. There's no Table.insert_row() method in the API.

A possible approach is to write a so-called "workaround function" that manipulates the underlying XML directly. You can get to any given XML element (e.g. <w:tbl> in this case or perhaps <w:tr>) from it's python-docx proxy object. For example:

tbl = table._tbl

Which gives you a starting point in the XML hierarchy. From there you can create a new element from scratch or by copying and use lxml._Element API calls to place it in the right position in the XML.

It's a little bit of an advanced approach, but probably the simplest option. There are no other Python packages out there that provide a more extensive API as far as I know. The alternative would be to do something in Windows with their COM API or whatever from VBA, possibly IronPython. That would only work at small scale (desktop, not server) running Windows OS.

A search on python-docx workaround function and python-pptx workaround function will find you some examples.

like image 185
scanny Avatar answered Nov 05 '22 13:11

scanny


You can insert row to the end of the table and then move it in another position as follows:

from docx import Document
doc = Document('your docx file')
t = doc.tables[0]
row0 = t.rows[0] # for example
row1 = t.rows[-1]
row0._tr.addnext(row1._tr)
like image 41
Иван Ежов Avatar answered Nov 05 '22 13:11

Иван Ежов