编辑代码

import tkinter as tk
from tkinter import filedialog
from openpyxl import load_workbook
from docx import Document
import os
import subprocess

# 定义黄色标亮的名称变量
highlighted_variables = ["我的苹果数", "要分的人员", "每个人分的的苹果数"]

# 更新文档的函数
def update_document():
    # 加载Excel文件
    excel_file = "分苹果数据源.xlsx"
    if not os.path.exists(excel_file):
        print("Excel文件不存在!")
        return
    wb = load_workbook(excel_file)
    sheet = wb["Sheet1"]  # 选择Sheet1

    # 查找表头行
    header_row = None
    for row in sheet.iter_rows(min_row=1, max_row=1, values_only=True):
        header_row = row
        break

    # 查找名称对应的数值
    results = {}
    for variable in highlighted_variables:
        if variable in header_row:
            col_index = header_row.index(variable) + 1  # 列索引(从1开始)
            value = sheet.cell(row=2, column=col_index).value  # 假设数据在第二行
            results[variable] = value

    # 加载Word文档
    doc_file = "分苹果.docx"
    if not os.path.exists(doc_file):
        print("Word文档不存在!")
        return
    doc = Document(doc_file)

    # 替换Word文档中的黄色标亮变量
    for paragraph in doc.paragraphs:
        for variable, value in results.items():
            if f"[«{variable}»]" in paragraph.text:
                paragraph.text = paragraph.text.replace(f"[«{variable}»]", str(value))

    # 保存修改后的Word文档
    output_file = "分苹果_更新后.docx"
    doc.save(output_file)
    print(f"文档已更新并保存为: {output_file}")

# 打开和编辑Excel文件的函数
def open_excel():
    excel_file = "分苹果数据源.xlsx"
    if os.path.exists(excel_file):
        subprocess.run(["start", "excel", excel_file], shell=True)
    else:
        print("Excel文件不存在!")

# 打开和编辑Word文档的函数
def open_word():
    doc_file = "分苹果.docx"
    if os.path.exists(doc_file):
        subprocess.run(["start", "winword", doc_file], shell=True)
    else:
        print("Word文档不存在!")

# 打开最新文档的函数
def open_latest_document():
    output_file = "分苹果_更新后.docx"
    if os.path.exists(output_file):
        subprocess.run(["start", "winword", output_file], shell=True)
    else:
        print("最新文档不存在!请先更新文档。")

# 创建主窗口
root = tk.Tk()
root.title("分苹果文档工具")
root.geometry("300x150")

# 添加按钮
btn_excel = tk.Button(root, text="数据源", command=open_excel, width=20, height=2)
btn_excel.pack(pady=10)

btn_word = tk.Button(root, text="文档模板", command=open_word, width=20, height=2)
btn_word.pack(pady=10)

btn_latest = tk.Button(root, text="最新文档", command=open_latest_document, width=20, height=2)
btn_latest.pack(pady=10)

# 运行主循环
root.mainloop()