我想使用 python docx 在 word 文件中的两个现有段落之间添加一个新段落
I want to add a new paragraph between two existing paragraph in word file using python docx
我的word文件里有
My first paragraph
My second paragraph
Third paragraph
Fourth paragraph
fifth paragraph
我的代码
from docx import Document
from docx.enum.text import WD_BREAK
document = Document('E:\world\2.docx')
paragraphs = document.paragraphs
paragraphs[2].runs[-1].add_break(WD_BREAK.LINE)
document.add_paragraph('new para between existing one ')
document.save('E:\world\2.docx')
执行后得到
My first paragraph
My second paragraph
Third paragraph
Fourth paragraph
fifth paragraph
new para between existing one
但我希望输出为
My first paragraph
My second paragraph
Third paragraph
new para between existing one
Fourth paragraph
fifth paragraph
您需要插入段落而不是添加段落。参见 this documentation for reference. Also more info about paragraph objects here。
请注意,您可能需要根据您正在编辑的 .docx
的实际内容更改我使用的 [5]
。
from docx import Document
from docx.enum.text import WD_BREAK
document = Document('E:\world\2.docx')
paragraphs = document.paragraphs
paragraphs[2].runs[-1].add_break(WD_BREAK.LINE)
paragraphs[5].insert_paragraph_before('new para between existing one ')
document.save('E:\world\2.docx')
我的word文件里有
My first paragraph
My second paragraph
Third paragraph
Fourth paragraph
fifth paragraph
我的代码
from docx import Document
from docx.enum.text import WD_BREAK
document = Document('E:\world\2.docx')
paragraphs = document.paragraphs
paragraphs[2].runs[-1].add_break(WD_BREAK.LINE)
document.add_paragraph('new para between existing one ')
document.save('E:\world\2.docx')
执行后得到
My first paragraph
My second paragraph
Third paragraph
Fourth paragraph
fifth paragraph
new para between existing one
但我希望输出为
My first paragraph
My second paragraph
Third paragraph
new para between existing one
Fourth paragraph
fifth paragraph
您需要插入段落而不是添加段落。参见 this documentation for reference. Also more info about paragraph objects here。
请注意,您可能需要根据您正在编辑的 .docx
的实际内容更改我使用的 [5]
。
from docx import Document
from docx.enum.text import WD_BREAK
document = Document('E:\world\2.docx')
paragraphs = document.paragraphs
paragraphs[2].runs[-1].add_break(WD_BREAK.LINE)
paragraphs[5].insert_paragraph_before('new para between existing one ')
document.save('E:\world\2.docx')