pythonpyqt详解(70.Python基于PyQt的批量修改WORD文档内容的小工具)
批量修改WORD文档内容的小工具(doctool)实现背景:
有同事在整理一个评估项目的文档,都是word格式,而且是旧版的doc格式,文档存放在一个总目录下,目录里有很多层子目录,文档的数量有数百个。现在需要把所有文档中的部分内容修改成新的内容。这里要注意的点就是要保持原文档格式不变。
手动一个一个打开文件,再去查找替换是可以,但头会很大而且效率很低,有没有办法快速实现批量修改?
本文就来写一下这个小工具,网上也有一些程序,但没有的封装成UI工具,使用起来不方便。本文就使用Python PyQt来实现这个小工具。
功能介绍:
1、一键批量实现DOC格式转DOCX格式(python的doc库不支持操作doc格式)
2、一键批量实现文件夹中(包括子文件夹)的docx文档内容修改。
一、界面UI设计根据要实现的功能,添加相应的元素,自适应窗口大小的布局。
UI
二、功能实现
完整代码
import sys
import os
from docx import document
from win32com import client
from PyQt5 import QtCore,QtGui,QtWidgets
from Ui_doctool import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow,Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.btnchoose.clicked.connect(self.choose_dir)
self.btnconvert.clicked.connect(self.convert_docx)
self.btnreplace.clicked.connect(self.replace_docx)
def choose_dir(self):
#打开文件夹,选择目录,返回目录
dirname = QtWidgets.QFileDialog.getExistingDirectory(self, "选择文件夹", "./")
self.statusBar().showMessage(dirname)
return dirname
def convert_docx(self):
#获取目录
dirname = self.choose_dir()
#遍历目录下的所有文件
for root, dirs, files in os.walk(dirname):
for file in files:
#获取文件名
filename = os.path.join(root, file)
#获取文件后缀
file_tuple = os.path.splitext(filename)
#判断文件后缀是否为doc
if file_tuple[1] == '.doc':
#转换为docx
#print(filename)
word = client.Dispatch('Word.Application')
doc = word.Documents.Open(filename)
doc.SaveAs(file_tuple[0] ".docx", 12)
doc.Close()
if not self.chkflag.isChecked():
#删除doc文件
os.remove(filename)
def replace_docx(self):
oldstr=self.editold.text()
newstr=self.editnew.text()
dirname = self.choose_dir()
#遍历目录下的所有文件
num=0
for root, dirs, files in os.walk(dirname):
for file in files:
#获取文件名
filename = os.path.join(root, file)
#获取文件后缀
file_tuple = os.path.splitext(filename)
#判断文件后缀是否为docx
if file_tuple[1] == '.docx':
document = Document(filename)
for i,para in enumerate(document.paragraphs):
oldtext=para.text.strip()
if oldtext:
lines=para.runs
if lines:
#清空原文本
for li,line in enumerate(lines):
lines[li].text=lines[li].text.replace(lines[li].text,"")
newtext=oldtext.replace(oldstr,newstr)
lines[0].text=newtext
#保存文件
document.save(filename)
num=num 1
self.statusBar().showMessage(f"{filename} 第{num}个文件替换完成,已保存")
self.statusBar().showMessage("替换完成,共替换" str(num) "个文件")
if __name__=="__main__":
app=QtWidgets.QApplication(sys.argv)
mywin=MainWindow()
mywin.setWindowTitle("doc tool")
mywin.show()
sys.exit(app.exec())
测试正常,第一个选择文件夹按钮有些多余。保留原文件是指保留doc格式。
运行
说明:程序也已打包成exe文件,有需要源码或打包好的程序,可以留言。
,免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com