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

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

第一步:

建立劳动合同文档模板。

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()


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

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

相关文章

2024年8月2日 星期五 多云

2024年8月2日 星期五 多云

最近这几天,真的是把我累坏了。每天的工作都是围绕着那些繁琐的政策文件,眼睛不停地在字里行间穿梭,大脑不停地分析解读着其中的每一个要点和含义。一堆堆的文件,仿佛没有尽头。我需要仔细地阅读每一行、每一段,...

2024年8月8日 星期四 多云

2024年8月8日 星期四 多云

最近,我一直专注于利用 AI 本地知识库来提升保险操作经办的便捷性。我们所做的工作,在吉林省是首家,虽不敢称全国领先,但意义重大。AI 本地知识库的搭建,旨在缓解我省企事业经办人员在五险一金知识检索方...

关于“中元节”祭祀烧纸看法和建议?

中元节是一个传统节日,对于祭祀烧纸这一习俗,我认为不应该完全禁止,但需要进行引导和管理。祭祀烧纸作为一种传统的祭祀方式,在一定程度上承载着人们对先人的缅怀和敬意,是文化传承的一部分。然而,无节制、无规...

长春地区 优秀经办人 AI 知识库大模型助力五险一金服务

长春地区 优秀经办人 AI 知识库大模型助力五险一金服务

本系统由 “百度文心智能体平台” 搭建。文心智能体平台 AgentBuilder,是百度推出的基于文心大模型的智能体平台,支持广大开发者根据自身行业领域、应用场景,选取不同类型的开发方式,打造大模...

企业电子劳动合同操作指南 (待编集)

企业电子劳动合同操作指南 (待编集)

网厅业务操作:启用电子劳动合同:企业用户在新签、续签或解除备案时选择是否启用电子劳动合同。添加电子签章授权操作员:企业启用电子劳动合同后,通过吉事办APP添加操作员并授权使用电子印章。企业授权电子签章...

Python 代码之 养老保险 个人缴费指数计算工具,3秒计算。

Python 代码之 养老保险 个人缴费指数计算工具,3秒计算。

演示代码不做最终输出效果。import pandas as pd import matplotlib.pyplot as plt fro...

发表评论    

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

服务热线

18686626826

微信客服

微信客服