批量自动生成Word程序
Posted 小蜗牛爱远行
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了批量自动生成Word程序相关的知识,希望对你有一定的参考价值。
-
程序需求:有个Word模板,有一批数据,需要根据数据批量生成多个Word
-
注意事项:
- 以下代码仅供参考,具体应用需要具体进行调试修改
- word模板中需要填值的地方插入书签,书签名称要与excel中的标题名称一样
- 如果存在多个一样的 替换内容:在书签后面加数字(例如Word中有点多个地方需要填姓名,就分别插入:姓名,姓名1,姓名2)
-
上代码:
# -------------------------------------- # - -*- coding:utf-8 -*- - # - Author : YYDS - # -------------------------------------- import logging, shutil, os, re import tkinter as tk from tkinter import filedialog import time import pandas as pd from win32com import client logging.basicConfig(level=logging.DEBUG, format='%(asctime)s line:%(lineno)d %(levelname)s : %(message)s', datefmt=' %Y-%m-%d %H:%M:%S', filename="info.log", filemode='a') #启动独立进程 APP=client.Dispatch('Word.Application') #设置是否可见,如果为false,则后台运行 APP.Visible=False class Yyds: def __init__(self): self.word_template_path = None @staticmethod def read_excel(): wd = tk.Tk() wd.withdraw() filename = filedialog.askopenfilename() df_data = pd.read_excel(filename) return df_data @staticmethod def get_word_path(): print('*' * 10 + '请选择生成的Word模板文件:' + '*' * 10) wd = tk.Tk() wd.withdraw() filename = filedialog.askopenfilename() return filename @staticmethod def get_target_dir(): print('*' * 10 + '请选择成果输出文件夹:' + '*' * 10) wd = tk.Tk() wd.withdraw() dir_name = filedialog.askdirectory() return dir_name def copy_word_template_path(self, srcfile, dstpath): # 复制函数 if not os.path.isfile(srcfile): print("%s not exist!" % (srcfile)) else: tpath, tname = os.path.split(dstpath) if not os.path.exists(tpath): os.makedirs(tpath) # 创建路径 shutil.copy(srcfile, dstpath) # 复制文件 return dstpath def start_work(self): df_data = self.read_excel() self.word_template_path = self.get_word_path() dir_name = self.get_target_dir() for index, row in df_data.iterrows(): #此处我固定死的,需要根据需求进行修改 if u"姓名" in row: name = row[u"姓名"] file_path = os.path.join(dir_name, name + ".doc") self.copy_word_template_path(self.word_template_path, file_path) # 打开word文档 word = APP.Documents.Open(dir_name + "/" + name + ".doc") # 获取所有书签 bookmarks = word.BookMarks #遍历获取到的书签 for i in bookmarks: bookmark_name = i.name i.Select() bookmark_name = ''.join(re.findall('[\\u4e00-\\u9fa5]', bookmark_name)) if bookmark_name in row: i.Range.Text = row[bookmark_name] time.sleep(0.5) #如果替换后不要这个书签了, 可以执行删除操作 # i.Delete() word.Close(-1) APP.Quit() if __name__ == '__main__': print('*' * 10 + '请选择需要处理的Excel文件' + '*' * 10) my_yyds = Yyds() my_yyds.start_work() print('*' * 10 + '结果输出完成!!!!!!' + '*' * 10)
-
升级版!!!
- 上图片
- 上代码
- 上图片
# --------------------------------------
# - -*- coding:utf-8 -*- -
# - Author : YYDS -
# --------------------------------------
import logging, shutil, os, re
import tkinter as tk
from tkinter import filedialog
from tkinter import ttk
from tkinter import font
import time
import pandas as pd
from win32com import client
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s line:%(lineno)d %(levelname)s : %(message)s',
datefmt=' %Y-%m-%d %H:%M:%S',
filename="info.log",
filemode='a')
#启动独立进程
APP=client.Dispatch('Word.Application')
#设置是否可见,如果为false,则后台运行
APP.Visible=False
root = tk.Tk()
root.title('Word生成器')
max_w, max_h = root.maxsize()
root.geometry(f'700x400+int((max_w - 500) / 2)+int((max_h - 300) / 2)') # 居中显示
root.resizable(width=False, height=False)
# 标签组件
label = tk.Label(root, text='选择Word:', font=('黑体', 15))
label.place(x=45, y=80)
# 标签组件
label2 = tk.Label(root, text='选择Excel:', font=('黑体', 15))
label2.place(x=45, y=155)
# 标签组件
label3 = tk.Label(root, text='选择文件夹:', font=('黑体', 15))
label3.place(x=45, y=225)
# 标签组件
label4 = tk.Label(root, text='生成进度', fg='green', font=('黑体', 15, font.BOLD))
label4.place(x=300, y=350)
# 输入框控件
entry_text = tk.StringVar()
entry = tk.Entry(root, textvariable=entry_text, font=('黑体', 12), width=50, state='readonly')
entry.place(x=155, y=85)
# 输入框控件
entry_text2 = tk.StringVar()
entry2 = tk.Entry(root, textvariable=entry_text2, font=('黑体', 12), width=50, state='readonly')
entry2.place(x=155, y=155)
# 输入框控件
entry_text3 = tk.StringVar()
entry3 = tk.Entry(root, textvariable=entry_text3, font=('黑体', 12), width=50, state='readonly')
entry3.place(x=155, y=225)
#进度条
progressbarOne = ttk.Progressbar(root)
progressbarOne.pack(side=tk.BOTTOM)
progressbarOne['length']=500
# 按钮控件
WORD_PATH = ''
EXCEL_PATH = ''
EXP_DIR = ''
class Yyds:
def __init__(self):
self.word_template_path = None
def clear_input(self):
entry_text.set('')
entry_text2.set('')
def get_word_path(self):
# 返回一个字符串,可以获取到任意文件的路径。
path1 = filedialog.askopenfilename(title='请选择Word模板路径')
entry_text.set(path1)
global WORD_PATH
WORD_PATH = path1
def get_excel_path(self):
path2 = filedialog.askopenfilename(title='请选择Excel文件路径')
entry_text2.set(path2)
global EXCEL_PATH
EXCEL_PATH = path2
def get_exp_dir(self):
path3 = filedialog.askdirectory(title='请选择成果输出文件夹')
entry_text3.set(path3)
global EXP_DIR
EXP_DIR = path3
def copy_word_template_path(self, srcfile, dstpath): # 复制函数
if not os.path.isfile(srcfile):
print("%s not exist!" % (srcfile))
else:
tpath, tname = os.path.split(dstpath)
if not os.path.exists(tpath):
os.makedirs(tpath) # 创建路径
shutil.copy(srcfile, dstpath) # 复制文件
return dstpath
def start_work(self):
df_data = pd.read_excel(EXCEL_PATH, converters=u'年利率': str)
progressbarOne['maximum'] = df_data.shape[0]
dir_name = EXP_DIR
for index, row in df_data.iterrows():
if u"姓名" in row:
name = row[u"姓名"]
file_path = os.path.join(dir_name, name + ".doc")
self.copy_word_template_path(WORD_PATH, file_path)
# 打开word文档
word = APP.Documents.Open(dir_name + "/" + name + ".doc")
# 获取所有书签
bookmarks = word.BookMarks
#遍历获取到的书签
for i in bookmarks:
bookmark_name = i.name
i.Select()
bookmark_name = ''.join(re.findall('[\\u4e00-\\u9fa5]', bookmark_name))
if bookmark_name in row:
i.Range.Text = row[bookmark_name]
time.sleep(0.5)
#如果替换后不要这个书签了, 可以执行删除操作
# i.Delete()
word.Close(-1)
progressbarOne['value'] = index + 1
root.update()
APP.Quit()
def select_word_path(self):
button = tk.Button(root, text='选择Word模板', font=('黑体', 13), bg="#94D8F6", command=self.get_word_path)
button.place(x=510, y=75)
def select_excel_path(self):
button2 = tk.Button(root, text='选择Excel数据', font=('黑体', 13), bg="#94D8F6", command=self.get_excel_path)
button2.place(x=510, y=155)
button3 = tk.Button(root, text='选择输出路径', font=('黑体', 13), bg="#94D8F6", command=self.get_exp_dir)
button3.place(x=510, y=220)
do_it = tk.Button(root, text="确定", font=('黑体', 13), fg="#138535", command=self.start_work)
do_it.place(x=230, y=270)
clear_it = tk.Button(root, text="取消", font=('黑体', 13), fg="#ED1C24", command=self.clear_input)
clear_it.place(x=400, y=270)
root.mainloop()
if __name__ == '__main__':
my_yyds = Yyds()
my_yyds.select_word_path()
my_yyds.select_excel_path()
以上是关于批量自动生成Word程序的主要内容,如果未能解决你的问题,请参考以下文章