python批量修改word文档页眉页脚

实现的目标

批量修改word文档的页眉和页脚

用到的python模块

pip install pywin32

脚本内容

import os
import win32com.client as win32
import pythoncom

path = u'D:\需替换'
old_name = u'哈哈哈'
new_name = u'嘿嘿嘿'
err_log = path + u'\head修改出错列表.txt'
def log(text):
    with open( err_log,"a+" ) as f:
        f.write(text)
        f.write('\n')

def change_header(path):
    ''' 更改文件的页眉页脚 '''
    pythoncom.CoInitialize()
    word = win32.Dispatch('Word.Application')
    word.Visible = 0
    word.DisplayAlerts = 0
    for parent, dirnames, filenames in os.walk(path):
        for fn in filenames:
            filedir = os.path.join(parent, fn)
            if fn.endswith('.docx'):
                print(filedir)
                try:
                    doc = word.Documents.Open( filedir )
                    a = word.ActiveDocument.Sections
                    n = 0
                    for i in range( len(a) ):
                        head = word.ActiveDocument.Sections[i].Headers[0]
                        old_head = str(head)
                        foot = word.ActiveDocument.Sections[i].Footers[0]
                        old_foot = str(foot)
                        #print( old_head )
                        if old_name in old_head:
                            new_head = old_head.replace( old_name, new_name )
                            #print( new_head )
                            word.ActiveDocument.Sections[i].Headers[0].Range.Find.ClearFormatting()
                            word.ActiveDocument.Sections[i].Headers[0].Range.Find.Replacement.ClearFormatting()
                            word.ActiveDocument.Sections[i].Headers[0].Range.Find.Execute( old_name, False, False, False, False, False, False, 1, False, new_name, 2 )

                        if old_name in old_foot:
                            new_foot = old_foot.replace( old_name, new_name )
                            #print( new_head )
                            word.ActiveDocument.Sections[i].Footers[0].Range.Find.ClearFormatting()
                            word.ActiveDocument.Sections[i].Footers[0].Range.Find.Replacement.ClearFormatting()
                            word.ActiveDocument.Sections[i].Footers[0].Range.Find.Execute( old_name, False, False, False, False, False, False, 1, False, new_name, 2 )
                        n = n+1
                    doc.Close()
                except Exception as e:
                    log(str(filedir))

change_header(path)


你可能感兴趣的:(python,文档处理)