如何使用Python将新数据附加到现有doc / docx文件

时间:2014-08-12 09:57:11

标签: python

我是python的新手,我正在尝试使用Python将新数据附加到现有的docx文件中。

from docx import Document # for Word document 
document = Document()
document.add_paragraph('My first paragraph')
document.add_paragraph("Second paragraph")
document.add_paragraph("Third paragraph")
document.add_paragraph("fourth paragraph")
document.add_paragraph("fifth paragraph") 

document.save("testDocmod.docx")

document = Document('testDocmod.docx')
paragraphs = document.paragraphs
incr=1
for paragraph in paragraphs:
    runs = paragraph.runs
    for run in runs:
        if(incr == 2):
            run.text = 'Updatd text'
        print run.text
    incr = incr + 1

但它只是更新第二个元素,而我需要在第二个元素之前附加它

1 个答案:

答案 0 :(得分:0)

根据您是否希望收到,您可以:
1)删除第二段的所有内容并重新创建

from docx import Document
document = Document('testDocmod.docx')
paragraphs = document.paragraphs

#Store content of second paragraph
text = paragraphs[1].text

#Clear content
paragraphs[1]._p.clear()

#Recreate second paragraph
paragraphs[1].add_run('Appended part ' + text)
document.save("testDocmod.docx")

结果:

My first paragraph

Appended part Second paragraph

Third paragraph

fourth paragraph

fifth paragraph

2)只需在第一段中添加文字:

from docx import Document
from docx.enum.text import WD_BREAK

document = Document('testDocmod.docx')
paragraphs = document.paragraphs

#Add break line after last run
paragraphs[0].runs[-1].add_break(WD_BREAK.LINE)
paragraphs[0].add_run('New text')
document.save("testDocmod.docx")

结果:

My first paragraph
New text

Second paragraph

Third paragraph

fourth paragraph

fifth paragraph