程序员面试代码

from win32com.client import Dispatch   # 导入win32com模块的client包下的函数
from win32com.client import constants  # 导入win32com模块的client包下的保存COM常量的类
from win32com.client import gencache   # 导入win32com模块的client包下的gencache()函数
import pythoncom                       # 导入封装了OLE自动化API的模块,该模块为win32com的子模块
import os                              # 导入系统功能模块

# 批量替换Word文档中的指定文字,包括页眉中的文字
def replaceall(filelist,targetpath,strold,strnew):
    errmark = False  # 标记是否报错,False表示没有报错,True表示报错
    try:
        # 调用线程初始化COM库,解决调用Word 2007时出现“尚未调用CoInitialize”错误的问题
        pythoncom.CoInitialize()
        gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
        w = Dispatch("Word.Application")        # 创建Word应用程序
        w.DisplayAlerts = 0            # 后台运行不显示、不警告
        for fullfilename in filelist:
            # 文档路径需要为绝对路径,因为Word启动后的当前路径不是调用脚本时的当前路径。
            try:
                doc = w.Documents.Open(fullfilename)   # 打开Word文档
                # 从绝对路径中分割路径和完整文件名
                filepath,fullname = os.path.split(fullfilename)
                fname,ext = os.path.splitext(fullname) # 从完整文件名中分割文件名和扩展名
                # 组合目标文件绝对路径
                targetfile = os.path.abspath(targetpath+"\\" + fname +".docx") 
                # 替换正文中的内容
                doc.Content.Find.Execute(FindText= strold,ReplaceWith=strnew,Replace=2)  
                '''
                替换页眉
                '''
                w.ActiveDocument.Sections(1).Headers(constants.wdHeaderFooterPrimary).Range.Find.ClearFormatting()
                w.ActiveDocument.Sections(1).Headers(constants.wdHeaderFooterPrimary).Range.Find.Replacement.ClearFormatting()
                w.ActiveDocument.Sections(1).Headers(constants.wdHeaderFooterPrimary).Range.Find.\
                            Execute(FindText = strold,MatchCase = False,MatchWholeWord = False,MatchWildcards=False, MatchSoundsLike= False, MatchAllWordForms=False,Forward=False,Wrap = 1,Format = False, ReplaceWith = strnew,Replace=2,MatchKashida=False,MatchDiacritics=False, MatchAlefHamza=False,MatchControl=False)
                # 需要保存才可以保留替换结果,如果想在原文件上修改可以使用doc.Save()方法
                doc.SaveAs(targetfile)   
                doc.Close(False)                       # 关闭文件
            except Exception as e:
                errmark = True                         # 标记是否出错的变量
                print(e)
        w.Quit(constants.wdDoNotSaveChanges)           # 关闭Word应用程序
        if not errmark:                                # 不出错时
            print("替换完毕!文件路径:",targetpath)
    except TypeError as e:
        print('出错了!')
        print(e)

if __name__ == '__main__':
    filelist =[os.path.abspath("test\\demo.docx"),os.path.abspath("test\\demo1.docx")]
    targetpath = os.path.abspath("new")  # 指定目标路径为当前项目根目录下的new目录
    strold = u"python"                    # 要替换的字符串
    strnew = u"Python"                    # 替换为的字符串
    replaceall(filelist,targetpath,strold,strnew)    # 替换Word文档中的指定内容

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荣华富贵8

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值