2025年4月14日 星期一 批量生成劳动合同PY代码

一颗大白菜1年前我的技能660

第一步:

建立劳动合同文档模板。

image.png

第二步:

整理表格数据。

image.png

第三步:

image.png

第四步:

查看文件

image.png

import tkinter as tk
from tkinter import filedialog, messagebox
from openpyxl import load_workbook
import os
import threading
from docx import Document


class WordDocumentGenerator:
    def __init__(self, root):
        self.root = root
        self.root.geometry("800x800")
        self.excel_file = None
        self.word_template = None
        self.output_dir = None
        self.stop_flag = False
        self.create_folders = tk.BooleanVar()
        self.prefix = tk.StringVar()
        self.suffix = tk.StringVar()
        self.selected_fields = []
        font_style = ("微软雅黑", 12)

        # 创建 GUI 组件
        tk.Label(root, text="选择 Excel 文件", font=font_style).pack(pady=10)
        self.excel_path_label = tk.Entry(root, width=50, state="readonly", font=font_style)
        self.excel_path_label.pack(pady=5)
        tk.Button(root, text="浏览", command=self.select_excel_file, font=font_style).pack(pady=5)

        tk.Label(root, text="选择 Word 模板", font=font_style).pack(pady=10)
        self.word_path_label = tk.Entry(root, width=50, state="readonly", font=font_style)
        self.word_path_label.pack(pady=5)
        tk.Button(root, text="浏览", command=self.select_word_template, font=font_style).pack(pady=5)

        tk.Label(root, text="选择输出目录", font=font_style).pack(pady=10)
        self.output_dir_label = tk.Entry(root, width=50, state="readonly", font=font_style)
        self.output_dir_label.pack(pady=5)
        tk.Button(root, text="浏览", command=self.select_output_directory, font=font_style).pack(pady=5)

        tk.Checkbutton(root, text="创建文件夹", variable=self.create_folders, font=font_style).pack(pady=10)

        tk.Label(root, text="前缀:", font=font_style).pack(pady=5)
        tk.Entry(root, textvariable=self.prefix, font=font_style).pack(pady=5)

        tk.Label(root, text="后缀:", font=font_style).pack(pady=5)
        tk.Entry(root, textvariable=self.suffix, font=font_style).pack(pady=5)

        tk.Button(root, text="生成 Word 文档", command=self.generate_word_docs, font=font_style).pack(pady=20)
        tk.Button(root, text="停止生成", command=self.stop_generating, font=font_style).pack(pady=10)

    def select_excel_file(self):
        self.excel_file = filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx;*.xls")])
        if self.excel_file:
            self.excel_path_label.config(state="normal")
            self.excel_path_label.delete(0, tk.END)
            self.excel_path_label.insert(0, self.excel_file)
            self.excel_path_label.config(state="readonly")

    def select_word_template(self):
        self.word_template = filedialog.askopenfilename(filetypes=[("Word files", "*.docx")])
        if self.word_template:
            self.word_path_label.config(state="normal")
            self.word_path_label.delete(0, tk.END)
            self.word_path_label.insert(0, self.word_template)
            self.word_path_label.config(state="readonly")

    def select_output_directory(self):
        self.output_dir = filedialog.askdirectory()
        if self.output_dir:
            self.output_dir_label.config(state="normal")
            self.output_dir_label.delete(0, tk.END)
            self.output_dir_label.insert(0, self.output_dir)
            self.output_dir_label.config(state="readonly")

    def load_excel_fields(self, excel_file):
        workbook = load_workbook(excel_file)
        sheet = workbook.active
        headers = [cell.value for cell in sheet[1]]
        return headers

    def generate_word_docs(self):
        if not self.excel_file or not self.word_template or not self.output_dir:
            messagebox.showerror("错误", "请选择 Excel 文件、Word 模板和输出目录")
            return
        self.stop_flag = False
        threading.Thread(target=self.fill_word_from_excel, args=(
            self.excel_file, self.word_template, self.output_dir, self.create_folders.get(),
            self.prefix.get(), self.suffix.get(), self.load_excel_fields(self.excel_file))).start()

    def stop_generating(self):
        self.stop_flag = True

    def fill_word_from_excel(self, excel_file, word_template, output_dir, create_folders, prefix, suffix,
                             selected_fields):
        workbook = load_workbook(excel_file)
        sheet = workbook.active
        template = Document(word_template)

        for row in sheet.iter_rows(min_row=2, values_only=True):
            if self.stop_flag:
                break
            data = dict(zip(selected_fields, row))
            new_doc = Document(word_template)
            for paragraph in new_doc.paragraphs:
                for key, value in data.items():
                    if key in paragraph.text:
                        for run in paragraph.runs:
                            run.text = run.text.replace(key, str(value))

            if create_folders:
                folder_name = os.path.join(output_dir, f"{prefix}{data.get(selected_fields[0], '')}{suffix}")
                os.makedirs(folder_name, exist_ok=True)
                output_path = os.path.join(folder_name, f"{prefix}{data.get(selected_fields[0], '')}{suffix}.docx")
            else:
                output_path = os.path.join(output_dir, f"{prefix}{data.get(selected_fields[0], '')}{suffix}.docx")
            new_doc.save(output_path)


if __name__ == "__main__":
    root = tk.Tk()
    app = WordDocumentGenerator(root)
    root.mainloop()


免责声明
如果您对本文有异议,请先阅读本站《免责声明》,如仍保持您个人观点可与本人联系。

你好优秀经办人微信公众号

相关文章

参加“优秀经办人”第一次在线考试中,也是最后一次考试。

参加“优秀经办人”第一次在线考试中,也是最后一次考试。

您于二零二四年度在本平台参加“优秀经办人”第一次在线考试中,凭借出色的个人业务知识,取得优异成绩,并获 100 分。在职工保险业务经办知识方面表现突出,完全符合“第一期...

作为企业保险经办人,操作职工保险工作流程图。要知晓 ……

作为企业保险经办人,操作职工保险工作流程图。要知晓 ……

本文十分适合新手参考操作。对于其他需补充问题,或建议。可联系本人。尚未设计完,临时存储私有服务器。哪个环节有问题,处理哪个环节。带有  logo  标志的,均附有地址链接。点击可查...

校门口定时拥堵何时休?集思广益求解交通困局

一、划定 “接学区” 和 “等候区”(一)区域规划接学区:根据学校周边道路和场地情况,在距离学校门口一定范围内划定专门的接学区。通常可以选择学校门口两侧的人行道、广场或空地等区域。接学区应设置明显的标...

2024年8月28日 星期三 每天都有病毒在你们身边

2024年8月28日 星期三 每天都有病毒在你们身边

不要相信所有发来的EXE执行文件。...

2024年8月30日 星期五 百度收录“优秀经办人”AI 知识库

2024年8月30日 星期五 百度收录“优秀经办人”AI 知识库

百度收录“优秀经办人”智能体,方便我平台用户了解吉林省保险政策及操作流程。如解答不如意,请联系系统管理员,一对一讲诉。AI知识库已接入“你好优秀经办人”微信公众号,也可直接在公众号内发送问题,AI为您...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

服务热线

18686626826

微信客服

微信客服