如何使用pywin32在doc中添加页眉和页脚?

时间:2017-05-30 12:14:52

标签: python header footer pywin32 doc

我知道如何从word doc获取页眉和页脚,但我想要做的是操纵那些页眉和页脚(比如添加更多文本或从页眉或页脚中删除现有文本)。我的问题是如何使用python程序和pywin32操纵页眉和页脚?请列出一些方法,以便我可以操纵页眉和页脚。 提前谢谢。

import win32com.client as win32
word = win32.Dispatch("Word.Application")
word.Visible = 0
word.Documents.Open("a.docx")
doc = word.ActiveDocument
footer = doc.sections[0].footers[0]    #get footer
header = doc.sections[0].headers[0]    #get header
print(str(header)+" "+str(footer))    #printing both

输出: 页眉页脚

1 个答案:

答案 0 :(得分:0)

这对我有用。 请记住,根据您的需要,格式化可能需要调整。

doc = word.ActiveDocument       
sections = doc.Sections
for section in sections:

    headersCollection = section.Headers

    for header in headersCollection:
        header.Range.Text = header.Range.Text + "hello world"
        print(header.Range.Text)