按照Excel内容生成word小工具
本帖最后由 w3812247 于 2023-5-13 17:09 编辑今天来公司加班,我把一堆excel中的内容按照word的模版,生成word。作为一位资深懒人,于是我就又开动了我的脑筋,改了改上次老王要的那个套红的程序。代码如下,有需要的也可以自己改改,增加一些功能。
成品和excel的例子已上传:
https://wwox.lanzout.com/b04246gve
密码:herz
"""
"""
from tkinter import *
from tkinter import filedialog,messagebox
from tkinter.ttk import *
from typing import Dict
import os
import pandas as pd
from docxtpl import DocxTemplate
class WinGUI(Tk):
widget_dic: Dict = {}
def __init__(self):
super().__init__()
self.__win()
self.widget_dic["tk_label_arrange"] = self.__tk_label_arrange(self)
self.widget_dic["tk_input_arrange"] = self.__tk_input_arrange(self)
self.widget_dic["tk_label_excel"] = self.__tk_label_excel(self)
self.widget_dic["tk_input_excel"] = self.__tk_input_excel(self)
self.widget_dic["tk_button_openexcel"] = self.__tk_button_openexcel(self)
self.widget_dic["tk_input_word"] = self.__tk_input_word(self)
self.widget_dic["tk_label_word"] = self.__tk_label_word(self)
# self.widget_dic["tk_button_openword"] = self.__tk_button_openword(self)
self.widget_dic["tk_label_info"] = self.__tk_label_info(self)
self.widget_dic["tk_button_lhld0n3u"] = self.__tk_button_lhld0n3u(self)
self.widget_dic["tk_select_box_lhldb7sn"] = self.__tk_select_box_lhldb7sn(self)
self.widget_dic["tk_label_lhldbccg"] = self.__tk_label_lhldbccg(self)
self.widget_dic["tk_label_lhle5h7h"] = self.__tk_label_lhle5h7h(self)
self.widget_dic["tk_label_lhlgfjup"] = self.__tk_label_lhlgfjup(self)
self.widget_dic["tk_input_name"] = self.__tk_input_name(self)
self.widget_dic["tk_label_name"] = self.__tk_label_name(self)
self.widget_dic["tk_label_lhlnz4v6"] = self.__tk_label_lhlnz4v6(self)
def __win(self):
self.title("excel生成word")
# 设置窗口大小、居中
width = 612
height = 400
screenwidth = self.winfo_screenwidth()
screenheight = self.winfo_screenheight()
geometry = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
self.geometry(geometry)
self.resizable(width=False, height=False)
# 自动隐藏滚动条
def scrollbar_autohide(self,bar,widget):
self.__scrollbar_hide(bar,widget)
widget.bind("<Enter>", lambda e: self.__scrollbar_show(bar,widget))
bar.bind("<Enter>", lambda e: self.__scrollbar_show(bar,widget))
widget.bind("<Leave>", lambda e: self.__scrollbar_hide(bar,widget))
bar.bind("<Leave>", lambda e: self.__scrollbar_hide(bar,widget))
def __scrollbar_show(self,bar,widget):
bar.lift(widget)
def __scrollbar_hide(self,bar,widget):
bar.lower(widget)
def __tk_label_arrange(self,parent):
label = Label(parent,text="excel中列名",anchor="center")
label.place(x=32, y=20, width=87, height=30)
return label
def __tk_input_arrange(self,parent):
ipt = Entry(parent)
ipt.place(x=130, y=20, width=449, height=30)
return ipt
def __tk_label_excel(self,parent):
label = Label(parent,text="excel文件",anchor="center")
label.place(x=30, y=70, width=85, height=30)
return label
def __tk_input_excel(self,parent):
ipt = Entry(parent)
ipt.place(x=130, y=70, width=388, height=30)
return ipt
def __tk_button_openexcel(self,parent):
btn = Button(parent, text="选择")
btn.place(x=530, y=70, width=50, height=30)
return btn
def __tk_input_word(self,parent):
ipt = Entry(parent)
ipt.place(x=130, y=170, width=388, height=30)
return ipt
def __tk_label_word(self,parent):
label = Label(parent,text="点此打开word模版文件",anchor="center")
label.place(x=320, y=120, width=153, height=30)
return label
# def __tk_button_openword(self,parent):
# btn = Button(parent, text="按钮")
# btn.place(x=530, y=170, width=50, height=30)
# return btn
def __tk_label_info(self,parent):
label = Label(parent,text="状态",anchor="center")
label.place(x=30, y=350, width=548, height=30)
return label
def __tk_button_lhld0n3u(self,parent):
btn = Button(parent, text="生成")
btn.place(x=280, y=300, width=50, height=30)
return btn
def __tk_select_box_lhldb7sn(self,parent):
cb = Combobox(parent, state="readonly")
cb['values'] = ("一行一word","一行一页")
cb.place(x=130, y=120, width=150, height=30)
return cb
def __tk_label_lhldbccg(self,parent):
label = Label(parent,text="生成方式",anchor="center")
label.place(x=30, y=120, width=70, height=30)
return label
def __tk_label_lhle5h7h(self, parent):
label = Label(parent, text="举例:序号,姓名,年龄,学分(英文逗号分割)", anchor="center")
label.place(x=130, y=0, width=262, height=24)
return label
def __tk_label_lhlgfjup(self, parent):
label = Label(parent, text="生成word文件名", anchor="center")
label.place(x=30, y=170, width=100, height=30)
return label
def __tk_input_name(self, parent):
ipt = Entry(parent)
ipt.place(x=156, y=220, width=362, height=30)
return ipt
def __tk_label_name(self, parent):
label = Label(parent, text="以列命名word", anchor="center")
label.place(x=30, y=220, width=109, height=30)
return label
def __tk_label_lhlnz4v6(self, parent):
label = Label(parent, text="举例:姓名(非必填),列内容不能有回车或特殊符号", anchor="center")
label.place(x=150, y=260, width=304, height=24)
return label
class Win(WinGUI):
def __init__(self):
super().__init__()
self.__event_bind()
def openexcel(self,evt):
strpath = filedialog.StringVar()
selected_file_path = filedialog.askopenfilename()# 使用askopenfilename函数选择单个文件
self.widget_dic["tk_input_excel"].delete(0, "end")
self.widget_dic["tk_input_excel"].insert(0, selected_file_path)
global dbpath
dbpath = selected_file_path
def openexample(self,evt):
createway=self.widget_dic["tk_select_box_lhldb7sn"].get()
print(createway)
if createway=="一行一页": #根据生成方式打开不同的模版
base_path = self.base_path('')
os.system('start ' + base_path + 'moban2.docx')
else:
base_path = self.base_path('')
os.system('start ' + base_path + 'moban1.docx')
# def openword(self,evt):
# strpath = filedialog.StringVar()
# selected_file_path = filedialog.askopenfilename()# 使用askopenfilename函数选择单个文件
# self.widget_dic["tk_input_word"].delete(0, "end")
# self.widget_dic["tk_input_word"].insert(0, selected_file_path)
# global dbpath
# dbpath = selected_file_path
def create(self,evt):
excelarr = len(self.widget_dic["tk_input_arrange"].get())
excellen = len(self.widget_dic["tk_input_excel"].get())
waylen = len(self.widget_dic["tk_select_box_lhldb7sn"].get())
wordlen = len(self.widget_dic["tk_input_word"].get())
namelen = len(self.widget_dic["tk_input_name"].get())
if excelarr<1 or excellen<1 or waylen<1 or wordlen<1:
messagebox.showinfo('错误','excel列名或excel文件或生成方式或生成名未填!')
return False
# if wordlen+namelen<1:
# messagebox.showinfo('生成名或列命名最少填一项!')
createway = self.widget_dic["tk_select_box_lhldb7sn"].get()
print(createway)
mobanpath = ""
if createway=="一行一页": #根据生成方式打开不同的模版
base_path = self.base_path('')
mobanpath = base_path + 'moban2.docx'
df = pd.read_excel(self.widget_dic["tk_input_excel"].get())# 这里的sheet_name是指定工作表 ,已放到当前文件夹了
# 把excel原文档数据通过jinja2模板匹配后,保存到word文档
arrangename = str(self.widget_dic["tk_input_arrange"].get()).split(",")
#print(df.values.tolist())
tpl = DocxTemplate(mobanpath)# 已放到当前文件夹了
tpl.render({'ps': self.changeenter(df.values.tolist())})# 参数是excel的列名
tpl.save(self.widget_dic["tk_input_word"].get() + '.docx')
else:
base_path = self.base_path('')
mobanpath = base_path + 'moban1.docx'
df = pd.read_excel(self.widget_dic["tk_input_excel"].get())# 这里的sheet_name是指定工作表 ,已放到当前文件夹了
arrangename = str(self.widget_dic["tk_input_arrange"].get()).split(",")
values = df.values.tolist()
ii = 1
for i in values:
print(i)
strstr = ""
iii = 1
for arr in arrangename:
if iii>1:
strstr =strstr+","+ "'"+arr+"':"+ "'"+str(i)+ "'"
else:
strstr = "'" + arr + "':" + str(i)
iii=iii+1
print(strstr)
strstr = strstr.replace("\n","\a") #替换word中的换行符,要不然是软回车
strstr = "{"+strstr+"}"
strstr = eval(strstr)
tpl = DocxTemplate(mobanpath)# 已放到当前文件夹了
tpl.render(strstr)# 参数是excel的列名
#以列命名word文件不为空
if len(self.widget_dic["tk_input_name"].get())>0:
tpl.save(str(strstr.get(str(self.widget_dic["tk_input_name"].get())))+ '.docx')
else:
tpl.save(self.widget_dic["tk_input_word"].get()+"_"+str(ii) + '.docx')
ii = ii+1
self.widget_dic["tk_label_info"]["text"] = "生成完毕,在当前程序目录查看!"
def __event_bind(self):
self.widget_dic["tk_button_openexcel"].bind('<Button-1>',self.openexcel)
self.widget_dic["tk_label_word"].bind('<Button-1>',self.openexample)
# self.widget_dic["tk_button_openword"].bind('<Button-1>',self.openword)
self.widget_dic["tk_button_lhld0n3u"].bind('<Button-1>',self.create)
def base_path(self,path):
if getattr(sys, 'frozen', None):
basedir = sys._MEIPASS
else:
basedir = os.path.dirname(__file__)
return os.path.join(basedir, path)
def changeenter(self,wordChars): #替换word中的换行符,要不然是软回车
stack = []
stack1 = []
for i in range(len(wordChars)):
# print(wordChars)
for ii in range(len(wordChars)):
word = str(wordChars).replace("\n", "\a")
stack.append(word)
stack1.append(stack)
stack = []
return stack1
if __name__ == "__main__":
win = Win()
win.mainloop()
进来学习下,谢谢楼主分享,感觉excel和word大部分都可以用邮件合并来解决,使用场景可能不多!:lol 厉害👍楼主 牛皮克拉斯 先标记 感觉用得到
收藏一下 感谢分享,奇葩小工具感觉很有点用,就是文件大了点 收藏了,不错的工具, 谢谢楼主。 感谢分享 你这个样搞是不是太费事 了?直接导入或者复制不就可以吗