当前位置: 首页 > news >正文

python 学习笔记20 批量修改页眉页脚

需求:修改指定目录下所有文件的页眉页脚,或者往里面添加内容。

1. 这里做了word的实现和excel的实现,如下:

需要先安装 pip3 install pywin32,另外页眉页脚格式设置可以参考:

word:

浅谈Word.Application,关于js操作word文档的使用_new word.application-CSDN博客

excel:

Python操作Excel教程(图文教程,超详细)Python xlwings模块详解,_xlwings教程-CSDN博客

import os
import xlwings as xw
import win32com.client as win32
import pythoncom#将需要替换页眉页脚的文档放到path下
path = r'C:\Users\d\Desktop\pdf改名脚本\22\2022年\test'
#原始页眉页脚内容
old_name = u'999'
#新页眉页脚内容
new_name = u'888'
#替换失败记录日志
err_log = path + u'\\head修改出错列表.txt'
def log(text):with open( err_log,"a+" ) as f:f.write(text)f.write('\n')def change_headerfooter(path):''' 更改文件的页眉页脚 '''pythoncom.CoInitialize()word = win32.Dispatch('Word.Application')#print(dir(word))word.Visible = 0word.DisplayAlerts = 0exapp = xw.App(visible=False, add_book=False)# excel = win32.Dispatch('Excel.Application')# excel.Visible = 0# excel.DisplayAlerts = 0for parent, dirnames, filenames in os.walk(path):for fn in filenames:filedir = os.path.join(parent, fn)#获取需替换目录下的docx结尾的文档名称if fn.endswith('.docx') or fn.endswith('.doc'):print(filedir)try:doc = word.Documents.Open( filedir )a = word.ActiveDocument.Sectionsn = 0for 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:if 1:#old_name存在页眉中时,进行进行替换#用于替换页眉#new_head = old_head.replace( old_name, new_name )#用于补充页眉#new_head = old_head + 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.Delete()#设置字体大小word.ActiveDocument.Sections[i].Headers[0].Range.Font.Size=20#设置对齐方式,0-左;1-中;2-右word.ActiveDocument.Sections[i].Headers[0].Range.ParagraphFormat.Alignment = 0word.ActiveDocument.Sections[i].Headers[0].Range.InsertAfter(new_name)#替换旧页眉#word.ActiveDocument.Sections[i].Headers[0].Range.Find.Execute( old_head, False, False, False, False, False, False, 1, False, new_name, 2 )#if old_name in old_foot:if 1:##old_name存在页脚中时,进行进行替换#new_foot = old_foot.replace( old_name, new_name )#new_foot = old_foot + new_nameword.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.Delete()word.ActiveDocument.Sections[i].Footers[0].Range.InsertAfter(new_name)#替换旧页脚#word.ActiveDocument.Sections[i].Footers[0].Range.Find.Execute( old_foot, False, False, False, False, False, False, 1, False, new_name, 2 )n = n+1doc.Close()except Exception as e:print(e)log(str(filedir))if fn.endswith('.xlsx') or fn.endswith('.xls'):print(filedir)try:ex = exapp.books.open(filedir)#print(dir(ex.sheets))sheet = ex.sheetsprint(sheet[0].name)if 'test' == sheet[0].name:print(sheet.name)else:#如果第一个sheet不是test则加一个test的sheetsheet.add('test',before=sheet[0].name)ex.save()ex.close()except Exception as e:log(str(filedir))word.Quit()exapp.quit()change_headerfooter(path)

补充一下:excel没有用pywin32去读写因为莫名其妙就是卡进程,无法对excel读写,可能和缓存的excel有关,如要编辑3.xlsx,则会卡一个~3.xlsx的进程无法结束。就换成了xlwings去读写。

http://www.lryc.cn/news/259923.html

相关文章:

  • IIS + Axios 跨域设置
  • 详细说说vuex
  • Qt之Ui样式表不影响子类的配置
  • Java集合--Map
  • C语言—每日选择题—Day48
  • 华为OD试题七(IPv4地址转换成整数、比赛的冠亚季军)
  • SVN优缺点详解及版本控制系统选型建议
  • 自己动手写数据库: select 查询语句对应查询树的构造和执行
  • 扬声器(喇叭)
  • 汇总大厂-校招/社招 Java面试题--持续补充更新中-大家别光收藏,要看起来,巩固基础,就是干呀!
  • 六. 函数
  • SpringBoot的Starter自动化配置,自己编写配置maven依赖且使用及短信发送案例
  • <蓝桥杯软件赛>零基础备赛20周--第9周--前缀和与差分
  • LeetCode-2487. 从链表中移除节点【栈 递归 链表 单调栈】
  • Redisson分布式锁原理分析
  • 【Linux】:线程(二)互斥
  • vscode报错Pylance client: couldn‘t create connection to server.
  • 智能优化算法应用:基于萤火虫算法3D无线传感器网络(WSN)覆盖优化 - 附代码
  • MacOS多屏状态栏位置不固定,程序坞不小心跑到副屏
  • Python:pipdeptree 语法介绍
  • 【问题处理】—— lombok 的 @Data 大小写区分不敏感
  • 跟着我学Python基础篇:08.集合和字典
  • Tomcat部署(图片和HTML等)静态资源时遇到的问题
  • 在接触新的游戏引擎的时候,如何能快速地熟悉并开发出一款新游戏?
  • 计网 - TCP四次挥手原理全曝光:深度解析与实战演示
  • 个人养老金知多少?
  • gpt3、gpt2与gpt1区别
  • PyQt6 QDateEdit日期控件
  • 【无线网络技术】——无线城域网(学习笔记)
  • RK3568平台 OTA升级原理