import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import openpyxl
from openpyxl.styles import Font, Alignment
import os
import warnings
# 常量
COLUMNS = ('序号', '部门', '班级', '姓名', '本人手机号', '班主任', '手机号', '备注')
FILE_NAME = "学生会某部成员信息.xlsx"
def import_from_excel(treeview, file_path):
if file_path:
try:
workbook = openpyxl.load_workbook(file_path)
sheet = workbook.active
treeview.delete(*treeview.get_children())
for row in sheet.iter_rows(values_only=True):
treeview.insert('', tk.END, values=row)
except Exception as e:
messagebox.showerror("错误", f"导入Excel时发生错误:{e}")
def export_to_excel(treeview, file_path):
if not file_path:
return
try:
workbook = openpyxl.Workbook()
sheet = workbook.active
# 合并 A1 到 F1 单元格
sheet.merge_cells('A1:F1')
title_cell = sheet['A1']
title_cell.value = "学生会某部成员信息"
title_cell.font = Font(name='黑体', size=20, bold=True)
title_cell.alignment = Alignment(horizontal='center', vertical='center')
for child in treeview.get_children():
row_data = treeview.item(child)['values']
sheet.append(row_data)
# 获取目录和文件名
initial_dir = os.getcwd()
full_file_path = filedialog.asksaveasfilename(
initialdir=initial_dir,
initialfile=FILE_NAME,
defaultextension=".xlsx",
filetypes=[("Excel files", "*.xlsx")],
encoding='utf-8',
title="保存文件"
)
if full_file_path:
workbook.save(full_file_path)
messagebox.showinfo("成功", "导出Excel成功!")
except Exception as e:
messagebox.showerror("错误", f"导出Excel时发生错误:{e}")
def sort_treeview(treeview, col='序号', reverse=False):
l = [(treeview.set(k, col), k) for k in treeview.get_children('')]
l.sort(reverse=reverse)
for index, (val, k) in enumerate(l):
treeview.move(k, '', index)
treeview.heading(col, command=lambda: sort_treeview(treeview, col, not reverse))
def add_person(treeview):
entry_window = tk.Toplevel()
entry_window.title("督察部录入")
frame = ttk.Frame(entry_window)
frame.pack(padx=10, pady=10)
labels_entries = {}
for i, col in enumerate(COLUMNS):
label = ttk.Label(frame, text=f"{col}:")
label.grid(row=i, column=0, padx=5, pady=5, sticky='e')
entry = ttk.Entry(frame)
entry.grid(row=i, column=1, columnspan=3, padx=5, pady=5, sticky='w')
labels_entries[col] = entry
def save_entry():
new_data = [labels_entries[col].get() for col in COLUMNS]
treeview.insert('', tk.END, values=new_data)
sort_treeview(treeview)
entry_window.destroy()
save_btn = ttk.Button(frame, text="保存", command=save_entry)
save_btn.grid(row=len(COLUMNS) + 1, columnspan=4, pady=10)
entry_window.wait_window()
def open_labor_department():
warnings.filterwarnings("ignore", category=UserWarning)
root = tk.Tk()
root.withdraw()
labor_window = tk.Toplevel(root)
labor_window.title("劳动部")
label = tk.Label(labor_window, text="欢迎进入劳动部")
label.pack(pady=20)
treeview = ttk.Treeview(labor_window)
treeview['columns'] = COLUMNS
treeview.column('#0', width=0, stretch=tk.NO)
for col in treeview['columns']:
treeview.column(col, anchor=tk.CENTER, width=80)
treeview.heading('#0', text='', anchor=tk.CENTER)
for col in treeview['columns']:
treeview.heading(col, text=col, anchor=tk.CENTER)
treeview.pack(side=tk.TOP, fill=tk.X)
btn_frame = tk.Frame(labor_window)
btn_frame.pack(fill=tk.X, ipady=5)
import_btn = ttk.Button(btn_frame, text="导入Excel", command=lambda: import_from_excel(treeview,
filedialog.askopenfilename(
filetypes=[("Excel files", "*.xlsx")])))
import_btn.pack(side=tk.LEFT, padx=(10, 0), expand=True)
export_btn = ttk.Button(btn_frame, text="导出Excel", command=lambda: export_to_excel(treeview,
filedialog.asksaveasfilename(
defaultextension=".xlsx")))
export_btn.pack(side=tk.LEFT, padx=(10, 0), expand=True)
add_btn = ttk.Button(btn_frame, text="录入人员", command=lambda: add_person(treeview))
add_btn.pack(side=tk.LEFT, padx=(10, 0), expand=True)
# 窗口关闭时停止主循环
labor_window.protocol("WM_DELETE_WINDOW", root.destroy)
screen_width = labor_window.winfo_screenwidth()
screen_height = labor_window.winfo_screenheight()
x = (screen_width // 2) - (300 // 2)
y = (screen_height // 2) - (200 // 2)
labor_window.geometry(f"600x400+{x}+{y}")
root.mainloop()
if __name__ == '__main__':
open_labor_department()