利用python批量修改word文档页眉

工作需要需要把一批word文档的页眉修改成统一名称,在网上看到一些文章,自己写了代码,记录免得未来忘了。

首先安装python-docx,命令行运行:

pip install python-docx -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

然后写一个枚举文件夹文件函数:

def findfilewith(folder,includestr=None):
    resultfileList=[]
    with os.scandir(folder) as it:
        for entry in it:
            if not entry.name.startswith('.') and entry.is_dir():
                filelist=findfilewith(entry.path,includestr)
                if len(filelist)>0:
                    resultfileList.extend(filelist)
            elif entry.is_file:
                if includestr is None:
                    resultfileList.append(entry.path)
                elif includestr in entry.name:
                    resultfileList.append(entry.path)               
                
    return resultfileList

第三写一个改一个文件页眉的函数

def replaceHeader(sReplaceText,sFileName):
    if sFileName.endswith(".docx") and ("~$" not in sFileName): 
        #形成docx对象
        document=Document(sFileName)
        #页眉
        header = document.sections[0].header 
        #页眉第一段
        paragraph = header.paragraphs[0] 
        #设置页眉,即使原来有页眉也可以替换        
        paragraph.text=sReplaceText
        #保存
        document.save(sFileName)    
    else:
        print("Not doc File")

整体函数:

import os
from os import path
from docx import Document

#sFolder预先定义想搜索的文件夹

docFileList=findfilewith(sFolder)

#replaceText想替换的内容,自定义

for file in docFileList:    
    replaceHeader(replaceText,file)

print("ok")

经过测试把文件夹word的页眉都修改成功了

参考的文档:python-docx设置页眉和页脚

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值