跳至正文

Cut and move Runs via python-docx

I want to cut and paste a run in one same document, but python-docx(1.1.0) don’t have the function.

Here are some related page, but it doesn’t solve the problem:
How do I copy the contents of a word document?
Copy paragraphs elements from one document to another

So I carefully read the source code and found that:

  1. You can process OXML object via paragraph._p and run._r, also call (paragraph/run)._element
  2. If you add a run._r to an other paragraph._p, it will be automatically removed from the origin paragraph

Here’s the code snippet:

# Get all_para and para_number
# all_para: all_para in document, para_number: current index in all_para
try:
    next_para = all_para[para_number + 1]
    new_para = next_para.insert_paragraph_before(style=para.style)
except IndexError:
    new_para = para._parent.add_paragraph(para.style)
run = para.runs[-1]
new_para._p.append(run._r)

# save document

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

🌍 Language