之前看网上的资料,大部分都是用 python-docx
库来删除 word 文档的页眉、页脚:
header.is_linked_to_previous = True
但是实际使用下来,问题不少,也不能保证所有页面(尤其是第一页)的页眉、页脚都被有效清除。
于是我想使用 win32com
,但网上的资料实在太少。经过一番探索,我得出了下面的方法:
首先安装:
pip install pypiwin32
编写 python 代码:
import os
from win32com import client
# 用来进行 word 文档的打开、保存、关闭操作
word = client.DispatchEx("Word.Application")
# 删除页眉、页脚的核心
wb = client.DispatchEx("Word.Basic")
def removeHeaderFooter(file):
'''
Para: file: word文档路径,需要包括文件名、拓展名
'''
# 打开文档,注意参数要是绝对路径,可以使用 os 库的方法进行转化
wordDoc = word.Documents.Open(os.path.abspath(file), ReadOnly=0)
# 调用 Word.Basic 来进行操作
# 注意后面没有表示函数的括号
wb.RemoveHeader
wb.RemoveFooter
# 保存文件,此外还可以为 SaveAs 函数增加 FileFormat=17 参数来保存为 pdf 文件(拓展名需要更改一下)
wordDoc.SaveAs(os.path.abspath(file))
# 注意,一定要关闭文件,因此建议将上面内容用 try 包起来,确保文件关闭
# 如果没有正确关闭,则下次无法正常打开
# 如有意外,可以将任务管理器中的 WINWORD 进程关闭,并将文件夹内的隐藏文件 ~$... .docx 删掉(可能是隐藏的)
wordDoc.Close()
if __name__ == '__main__':
removeHeaderFooter('test.docx')
如果需要遍历文件夹内所有 word 文件:
# 遍历文件夹
for name in os.listdir(path):
# 判断是文件,且是 word 文件
if os.path.isfile(os.path.join(path, name)) and name.split('.')[-1].lower() in ['doc', 'docx']:
print(f'{name}:removing header and footer...')
removeHeaderFooter(os.path.join(path, name))
本文原创,转载请注明:https://blog.youkuaiyun.com/swkfk/article/details/113856618