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_file = "分苹果数据源.xlsx"
if not os.path.exists(excel_file):
print("Excel文件不存在!")
return
wb = load_workbook(excel_file)
sheet = wb["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
value = sheet.cell(row=2, column=col_index).value
results[variable] = value
doc_file = "分苹果.docx"
if not os.path.exists(doc_file):
print("Word文档不存在!")
return
doc = Document(doc_file)
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))
output_file = "分苹果_更新后.docx"
doc.save(output_file)
print(f"文档已更新并保存为: {output_file}")
def open_excel():
excel_file = "分苹果数据源.xlsx"
if os.path.exists(excel_file):
subprocess.run(["start", "excel", excel_file], shell=True)
else:
print("Excel文件不存在!")
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()