How to replace the paragraph with another?

Viewed 130

I would like to replace the table with another table in another docx file. And during the searching, I found the method that down blow can delete the whole table(paragraph) easily.

doc = docx.Document('test.docx')

def delete_paragraph(paragraph):
  p = paragraph._element
  p.getparent().remove(p)
  p._p = p._element = None

delete_paragraph(doc.table[3])

So, I guess it's possible to replace, too.

And I try to code blow:

doc = docx.Document('test.docx')
stand = docx.Document('stand.docx')

def replace_paragraph(p1, p2):
  p1.element = p2._element

replace_paragraph(doc.tables[3],stand.tables[0])

But it didn't work. How can I do ?

===UPDATE===

I found another method blow.

from copy import deepcopy

def copy_table_after(table, paragraph):
  tbl, p = table._tbl, paragraph._p
  new_tbl = deepcopy(tbl)
  p.addnext(new_tbl)

First use delete_paragraph to delete the old table, then use copy_table_after to copy the new table.

However, this way has to know the paragraph location of the old table.

If someone know the better way, please tell me, thank you.

0 Answers
Related