In python-docx how do I delete a table row?

白昼怎懂夜的黑 提交于 2020-05-15 10:54:19

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/55545494/in-python-docx-how-do-i-delete-a-table-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!