# -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 10:16:35 2020
需要先安装WPS或者OFFICE软件,自动调用对应API操作。直接就是py文件源代码,在python环境下运行即可。
主要用于将一大堆word文件合并在一个文件中,常用于在一堆文件中进行搜索,只支持docx文件,对于doc格式文件,可以先用另外一个程序自动转成docx。自己去根据情况修改dir_path等 路径即可。
@author: w
"""
import os
from os.path import abspath
from win32com import client
def main(files, final_docx):
# 启动word应用程序
word = client.gencache.EnsureDispatch("Word.Application")
word.Visible = True
# 新建空白文档
new_document = word.Documents.Add()
for fn in files:
# 打开要合并的每个文件,复制其中的内容到剪切板,然后关闭文件
fn = abspath(fn)
temp_document = word.Documents.Open(fn)
word.Selection.WholeStory()
word.Selection.Copy()
temp_document.Close()
# 粘贴到新文档的最后
new_document.Range()
word.Selection.Delete()
word.Selection.Paste()
# 保存最终文件,关闭Word应用程序
new_document.SaveAs(final_docx)
new_document.Close()
word.Quit()
def find_file(path, ext, file_list=[]):
dir = os.listdir(path)
for i in dir:
i = os.path.join(path, i)
if os.path.isdir(i):
find_file(i, ext, file_list)
else:
if ext == os.path.splitext(i)[1]:
file_list.append(i)
return file_list
#先全部转换为docx文件,再合并
dir_path = "D:\我的文档\桌面\附件1文件"#批量转换文件夹
ext = ".docx"
file_list = find_file(dir_path, ext)
main(file_list,r"D:\我的文档\桌面\附件1文件\result.docx")
print(file_list)
自动将多个word文件合并成一个word文件,基于python
最新推荐文章于 2024-01-19 14:14:52 发布