7

I can't figure out how to delete a table row in python-docx. Specifically, my tables come in with a header row and a row that has a special token stored in the text of the first cell. I search for tables with the token and then fill in a bunch of rows of the table. But how do I delete row 1, which has the token, before adding new rows? I tried

table.rows[1].Delete() and table.rows = table.rows[0:1]

The first one fails with an unrecognized function (the documentation refers to this function in the Microsoft API, but I don't know what that means). The second one fails because table.rows is read-only, as the documentation says.

So how do I do it?

All The Rage
  • 743
  • 5
  • 24

4 Answers4

12

This functionality is not built-in, which really shocks me. As I search forums I find many people asking for this over the last five years. However, a workaround exists and here it is:

def remove_row(table, row):
    tbl = table._tbl
    tr = row._tr
    tbl.remove(tr)
    
row = table.rows[n]
remove_row(table, row)
ToTamire
  • 1,425
  • 1
  • 13
  • 23
All The Rage
  • 743
  • 5
  • 24
1

The answer by All the Rage did not work for me unfortunately. However, I was able to remove rows and columns as follows:

from  docx  import  Document
w=Document("path")
table_1=w.tables[0]

# delete row 
print(len(table_1.rows))
row2=table_1.rows[1]
row2._element.getparent().remove(row2._element)
print(len(table_1.rows))

# delete column 
col=table_1.table.columns[1]
for  cell in  col.cells:
    cell._element.getparent().remove(cell._element)
John_Doe
  • 95
  • 1
  • 11
1

You can use this function :

from docx import Document

document = Document('YOUR_DOCX')

def Delete_row_in_table(table, row):
    document.tables[table]._tbl.remove(document.tables[table].rows[row]._tr)

Delete_row_in_table(0, 0)

document.save('OUT.docx')
Liam-Nothing
  • 167
  • 8
1

I made this video to show how to do this easily because it confused me. https://www.youtube.com/watch?v=qA5QRXwAt2I

    Table = document.tables[0]
    RowA=Table.rows[0]

    table_element = Table._tbl
    table_element.remove(RowA._tr)

The code above removes the first row from the first table. You have to alter the xml elements there isnt a way to do it through the API for docx.