XML元素或python-docx.如何删除特定的行



我找不到如何删除python-docx中的特定行。

我需要删除文档表中第三行之后的所有行。

我发现如何使用xml元素删除特定行(例如第三行):

import docx
from docx import Document
document = Document('filename')
table = document.tables[0]
rowA=table.rows[3]
table_element=table._tbl
row_element=rowA._tr
table_element.remove(row_element)
document.save('filename')

如何删除第3行之后的所有行?

还没有测试过这段代码,但我猜您可以使用getnext()[1]方法来遍历所有剩余的行。getnext如文档中所说:Returns the following sibling of this element or None.

...
row_element = rowA._tr
next_row = row_element.getnext()
while next_row is not None:
table_element.remove(next_row)
next_row = row_element.getnext()
...

注意:这段代码的工作假设只有表行作为兄弟元素(可能有书签等),这可能是有意义的添加检查if next_row.tag == '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tr'

最新更新