功能說明:以下是一個使用Tkinter和Pandas實現的完整示例,支持Excel數據讀取、雙表格展示和高級條件篩選功能:
1.文件操作:點擊"打開文件"按鈕選擇Excel文件(支持.xlsx和.xls格式),自動加載數據到左側表格。輸入Pandas兼容的查詢條件,點擊"執行篩選"查看結果,點擊"清空條件"重置篩選結果。
2.數據展示:左側表格顯示原始數據,右側表格顯示篩選結果,自動適應列寬,支持垂直滾動。
3.高級篩選:數值比較:Age >= 25,字符串包含:Name.str.contains(“張”),多條件組合:(Salary > 8000) & (Department == “銷售部”),日期篩選:Join_Date > “2023-01-01”,在條件輸入框使用Pandas查詢語法,例如:點擊"執行篩選"按鈕應用條件,點擊"清空條件"按鈕重置篩選。
4.錯誤處理:文件讀取錯誤提示,條件語法錯誤提示,空條件警告。
5.數據庫保存功能:原始數據(JSON格式),保存時間戳(精確到秒),新增"保存結果"按鈕,自動創建SQLite數據庫文件(data_records.db),存儲結構包含:每次保存記錄當前系統時間。
6.數據庫查看功能:點擊"查看歷史"按鈕彈出歷史記錄窗口,顯示保存時間和記錄數量,雙擊條目可查看詳細數據,詳細數據顯示原始保存的表格格式。
7.條件收藏功能:新增收藏條件按鈕,支持為當前條件命名保存,下拉選擇框可快速調用歷史條件,自動同步數據庫中的收藏條件。
# -*- coding: utf-8 -*-
# @Author : 小紅牛
# 微信公眾號:WdPython
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, simpledialog
import pandas as pd
import sqlite3
from datetime import datetimeclass ExcelViewerApp:def __init__(self, root):self.root = rootself.root.title("Excel數據加載+分析1.0")self.df = pd.DataFrame()self.filtered_df = pd.DataFrame()self.saved_conditions = []# 初始化數據庫self.init_db()self.load_saved_conditions()# 創建界面組件self.create_widgets()self.setup_layout()self.setup_style()def init_db(self):"""初始化數據庫連接和表結構"""self.conn = sqlite3.connect('data_records.db')self.cursor = self.conn.cursor()# 結果表self.cursor.execute('''CREATE TABLE IF NOT EXISTS results(id INTEGER PRIMARY KEY AUTOINCREMENT,record_data TEXT,save_time TIMESTAMP)''')# 條件表(增加唯一約束)self.cursor.execute('''CREATE TABLE IF NOT EXISTS saved_conditions(id INTEGER PRIMARY KEY AUTOINCREMENT,condition_name TEXT UNIQUE,condition_expr TEXT,save_time TIMESTAMP)''')self.conn.commit()def load_saved_conditions(self):"""加載收藏條件"""self.cursor.execute("SELECT condition_name, condition_expr FROM saved_conditions ORDER BY save_time DESC")self.saved_conditions = self.cursor.fetchall()def create_widgets(self):"""創建所有界面組件"""# 工具欄self.toolbar = ttk.Frame(self.root)self.open_btn = ttk.Button(self.toolbar, text="打開文件", command=self.open_file)self.save_btn = ttk.Button(self.toolbar, text="保存數據", command=self.save_to_db)self.history_btn = ttk.Button(self.toolbar, text="查看數據", command=self.show_history)self.manage_btn = ttk.Button(self.toolbar, text="管理條件", command=self.manage_conditions)self.clear_btn = ttk.Button(self.toolbar, text="清空條件", command=self.clear_condition)# 條件輸入區self.condition_frame = ttk.LabelFrame(self.root, text="篩選條件")self.condition_combo = ttk.Combobox(self.condition_frame,values=[c[0] for c in self.saved_conditions],width=25,state="readonly")self.condition_combo.bind("<<ComboboxSelected>>", self.select_condition)self.condition_entry = ttk.Entry(self.condition_frame, width=50)self.save_condition_btn = ttk.Button(self.condition_frame, text="收藏條件", command=self.save_condition)self.search_btn = ttk.Button(self.condition_frame, text="執行篩選", command=self.filter_data)# 示例條件文本框self.example_frame = ttk.LabelFrame(self.root, text="條件命令示例(cv可復制)")self.example_text = tk.Text(self.example_frame,height=3,width=60,wrap=tk.WORD,bg='#F7F7F7',relief=tk.FLAT)self.example_text.insert(tk.END,"1.數值比較:工資 >= 9000,工資 == 8000,工資.between(9000, 15000)\n""2.文本匹配:姓名.str.contains('張'),部門 == '市場部'\n""3.多條件:工資 >= 9000 & 入職日期 > '2025-01-18'\n")self.example_text.configure(state=tk.DISABLED)# 數據表格self.tree_frame = ttk.Frame(self.root)self.original_tree = ttk.Treeview(self.tree_frame, show="headings")self.result_tree = ttk.Treeview(self.tree_frame, show="headings")# 滾動條self.original_scroll = ttk.Scrollbar(self.tree_frame, orient="vertical", command=self.original_tree.yview)self.result_scroll = ttk.Scrollbar(self.tree_frame, orient="vertical", command=self.result_tree.yview)def setup_layout(self):"""布局組件"""# 工具欄self.toolbar.pack(fill=tk.X, padx=5, pady=5)self.open_btn.pack(side=tk.LEFT, padx=2)self.save_btn.pack(side=tk.LEFT, padx=2)self.history_btn.pack(side=tk.LEFT, padx=2)self.manage_btn.pack(side=tk.LEFT, padx=2)self.clear_btn.pack(side=tk.LEFT, padx=2)# 條件輸入區self.condition_frame.pack(fill=tk.X, padx=5, pady=5)self.condition_combo.pack(side=tk.LEFT, padx=2)self.condition_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=2, pady=2)self.save_condition_btn.pack(side=tk.LEFT, padx=2)self.search_btn.pack(side=tk.LEFT, padx=2)# 示例文本框self.example_frame.pack(fill=tk.X, padx=5, pady=5)self.example_text.pack(padx=5, pady=5, fill=tk.BOTH, expand=True)# 表格區self.tree_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)self.original_tree.grid(row=0, column=0, sticky="nsew")self.original_scroll.grid(row=0, column=1, sticky="ns")self.result_tree.grid(row=0, column=2, sticky="nsew")self.result_scroll.grid(row=0, column=3, sticky="ns")# 列權重self.tree_frame.columnconfigure(0, weight=1)self.tree_frame.columnconfigure(2, weight=1)self.tree_frame.rowconfigure(0, weight=1)def setup_style(self):"""配置界面樣式"""style = ttk.Style()style.configure("Treeview", rowheight=28, font=('微軟雅黑', 10))style.configure("Treeview.Heading", font=('微軟雅黑', 10, 'bold'))style.configure("TButton", padding=6, font=('微軟雅黑', 9))style.configure("TLabelFrame", font=('微軟雅黑', 9, 'bold'))style.configure("TEntry", font=('微軟雅黑', 10))def open_file(self):"""打開Excel文件并加載數據"""file_path = filedialog.askopenfilename(filetypes=[("Excel文件", "*.xlsx *.xls"), ("所有文件", "*.*")])if file_path:try:self.df = pd.read_excel(file_path)self.update_treeview(self.original_tree, self.df)messagebox.showinfo("成功", f"成功加載文件:{file_path}")except Exception as e:messagebox.showerror("錯誤", f"文件讀取失敗:{str(e)}")def update_treeview(self, tree, dataframe):"""更新Treeview組件顯示數據"""# 清空現有數據tree.delete(*tree.get_children())# 配置列columns = list(dataframe.columns)tree["columns"] = columnsfor col in columns:tree.heading(col, text=col)tree.column(col, width=100, anchor="w", minwidth=50)# 插入數據for _, row in dataframe.iterrows():values = [self.format_value(v) for v in row.values]tree.insert("", "end", values=values)def format_value(self, value):"""格式化顯示值"""if pd.isna(value):return ""if isinstance(value, (float, int)):return round(value, 4)if isinstance(value, datetime):return value.strftime("%Y-%m-%d")return str(value)[:50] # 截斷長字符串def filter_data(self):"""執行數據篩選"""condition = self.condition_entry.get().strip()if not condition:messagebox.showwarning("輸入錯誤", "請輸入篩選條件")returntry:self.filtered_df = self.df.query(condition, engine='python')self.update_treeview(self.result_tree, self.filtered_df)except Exception as e:messagebox.showerror("條件錯誤", f"無效的篩選條件:\n{str(e)}")def save_to_db(self):"""保存篩選結果到數據庫"""if self.filtered_df.empty:messagebox.showwarning("保存錯誤", "沒有可保存的篩選結果")returntry:# 轉換為JSON格式json_data = self.filtered_df.to_json(orient='records', force_ascii=False)save_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")# 插入數據庫self.cursor.execute("INSERT INTO results (record_data, save_time) VALUES (?, ?)",(json_data, save_time))self.conn.commit()messagebox.showinfo("保存成功",f"成功保存 {len(self.filtered_df)} 條記錄\n保存時間:{save_time}")except Exception as e:messagebox.showerror("保存失敗", f"數據庫操作失敗:{str(e)}")def show_history(self):"""顯示歷史記錄窗口"""history_win = tk.Toplevel(self.root)history_win.title("歷史保存記錄")history_win.geometry("600x400")# 創建表格tree = ttk.Treeview(history_win, columns=("time", "count"), show="headings")tree.heading("time", text="保存時間")tree.heading("count", text="記錄數")tree.column("time", width=200)tree.column("count", width=100, anchor="center")# 滾動條scroll = ttk.Scrollbar(history_win, orient="vertical", command=tree.yview)tree.configure(yscrollcommand=scroll.set)# 布局tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)scroll.pack(side=tk.RIGHT, fill=tk.Y)# 加載數據self.cursor.execute("SELECT save_time, record_data FROM results ORDER BY save_time DESC")for save_time, data in self.cursor.fetchall():count = len(pd.read_json(data))display_time = datetime.strptime(save_time, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %H:%M")tree.insert("", "end", values=(display_time, count))# 雙擊查看詳情def on_double_click(event):selected = tree.selection()if selected:item = tree.item(selected[0])time_str = item["values"][0]self.show_history_detail(time_str)tree.bind("<Double-1>", on_double_click)def show_history_detail(self, time_str):"""顯示歷史記錄詳情"""detail_win = tk.Toplevel(self.root)detail_win.title(f"記錄詳情 - {time_str}")detail_win.geometry("800x600")# 查詢數據庫self.cursor.execute("SELECT record_data FROM results WHERE save_time LIKE ?",(f"{time_str}%",))result = self.cursor.fetchone()if not result:messagebox.showerror("錯誤", "找不到對應的記錄數據")return# 創建表格df = pd.read_json(result[0])tree = ttk.Treeview(detail_win, show="headings")scroll_x = ttk.Scrollbar(detail_win, orient="horizontal", command=tree.xview)scroll_y = ttk.Scrollbar(detail_win, orient="vertical", command=tree.yview)tree.configure(xscrollcommand=scroll_x.set, yscrollcommand=scroll_y.set)# 配置列tree["columns"] = list(df.columns)for col in df.columns:tree.heading(col, text=col)tree.column(col, width=120, minwidth=80, anchor="w")# 插入數據for _, row in df.iterrows():values = [self.format_value(v) for v in row.values]tree.insert("", "end", values=values)# 布局tree.pack(side=tk.TOP, fill=tk.BOTH, expand=True)scroll_y.pack(side=tk.RIGHT, fill=tk.Y)scroll_x.pack(side=tk.BOTTOM, fill=tk.X)def save_condition(self):"""保存當前篩選條件"""condition = self.condition_entry.get().strip()if not condition:messagebox.showwarning("輸入錯誤", "當前沒有可保存的條件")return# 獲取條件名稱name = simpledialog.askstring("保存條件", "請輸入條件名稱:", parent=self.root)if not name:return# 檢查重名self.cursor.execute("SELECT 1 FROM saved_conditions WHERE condition_name=?", (name,))if self.cursor.fetchone():messagebox.showerror("保存失敗", "該名稱已存在,請使用其他名稱")returntry:# 插入數據庫save_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")self.cursor.execute("INSERT INTO saved_conditions (condition_name, condition_expr, save_time) VALUES (?, ?, ?)",(name, condition, save_time))self.conn.commit()# 更新界面self.load_saved_conditions()self.condition_combo["values"] = [c[0] for c in self.saved_conditions]messagebox.showinfo("保存成功", "條件已成功收藏!")except Exception as e:messagebox.showerror("保存失敗", f"數據庫錯誤:{str(e)}")def select_condition(self, event):"""選擇已保存的條件"""selected_name = self.condition_combo.get()for name, expr in self.saved_conditions:if name == selected_name:self.condition_entry.delete(0, tk.END)self.condition_entry.insert(0, expr)breakdef manage_conditions(self):"""打開條件管理窗口"""manage_win = tk.Toplevel(self.root)manage_win.title("管理收藏條件")manage_win.geometry("600x400")# 條件列表tree = ttk.Treeview(manage_win, columns=("name", "expr"), show="headings", selectmode="browse")tree.heading("name", text="條件名稱")tree.heading("expr", text="條件表達式")tree.column("name", width=150)tree.column("expr", width=400)# 操作按鈕btn_frame = ttk.Frame(manage_win)edit_btn = ttk.Button(btn_frame, text="編輯", command=lambda: self.edit_condition(tree, manage_win))delete_btn = ttk.Button(btn_frame, text="刪除", command=lambda: self.delete_condition(tree))# 布局tree.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)btn_frame.pack(pady=5)edit_btn.pack(side=tk.LEFT, padx=5)delete_btn.pack(side=tk.LEFT, padx=5)# 加載數據for name, expr in self.saved_conditions:tree.insert("", "end", values=(name, expr))def edit_condition(self, tree, parent_win):"""編輯選中條件"""selected = tree.selection()if not selected:messagebox.showwarning("提示", "請先選擇一個條件")returnold_name, old_expr = tree.item(selected[0], "values")# 創建編輯對話框edit_win = tk.Toplevel(parent_win)edit_win.title("編輯條件")# 輸入組件ttk.Label(edit_win, text="名稱:").grid(row=0, column=0, padx=5, pady=5, sticky="e")name_entry = ttk.Entry(edit_win, width=30)name_entry.insert(0, old_name)name_entry.grid(row=0, column=1, padx=5, pady=5)ttk.Label(edit_win, text="表達式:").grid(row=1, column=0, padx=5, pady=5, sticky="e")expr_entry = ttk.Entry(edit_win, width=50)expr_entry.insert(0, old_expr)expr_entry.grid(row=1, column=1, padx=5, pady=5)def save_changes():new_name = name_entry.get().strip()new_expr = expr_entry.get().strip()if not new_name or not new_expr:messagebox.showwarning("輸入錯誤", "名稱和表達式不能為空")returntry:# 檢查名稱沖突if new_name != old_name:self.cursor.execute("SELECT 1 FROM saved_conditions WHERE condition_name=?", (new_name,))if self.cursor.fetchone():messagebox.showerror("錯誤", "名稱已存在")return# 更新數據庫self.cursor.execute("UPDATE saved_conditions SET condition_name=?, condition_expr=? WHERE condition_name=?",(new_name, new_expr, old_name))self.conn.commit()# 更新界面self.load_saved_conditions()self.condition_combo["values"] = [c[0] for c in self.saved_conditions]tree.item(selected[0], values=(new_name, new_expr))edit_win.destroy()messagebox.showinfo("成功", "條件已更新")except Exception as e:messagebox.showerror("錯誤", f"更新失敗:{str(e)}")ttk.Button(edit_win, text="保存", command=save_changes).grid(row=2, column=1, pady=10)def delete_condition(self, tree):"""刪除選中條件"""selected = tree.selection()if not selected:messagebox.showwarning("提示", "請先選擇一個條件")returncondition_name = tree.item(selected[0], "values")[0]if messagebox.askyesno("確認刪除", f"確定要刪除條件 '{condition_name}' 嗎?"):try:self.cursor.execute("DELETE FROM saved_conditions WHERE condition_name=?", (condition_name,))self.conn.commit()tree.delete(selected[0])self.load_saved_conditions()self.condition_combo["values"] = [c[0] for c in self.saved_conditions]messagebox.showinfo("成功", "條件已刪除")except Exception as e:messagebox.showerror("錯誤", f"刪除失敗:{str(e)}")def save_condition(self):"""保存當前條件"""condition = self.condition_entry.get().strip()if not condition:messagebox.showwarning("輸入錯誤", "當前沒有可保存的條件")returnname = simpledialog.askstring("保存條件", "請輸入條件名稱:", parent=self.root)if not name:return# 檢查重復self.cursor.execute("SELECT 1 FROM saved_conditions WHERE condition_name=?", (name,))if self.cursor.fetchone():messagebox.showerror("錯誤", "該名稱已存在")returntry:save_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")self.cursor.execute("INSERT INTO saved_conditions VALUES (NULL, ?, ?, ?)",(name, condition, save_time))self.conn.commit()# 更新界面self.load_saved_conditions()self.condition_combo["values"] = [c[0] for c in self.saved_conditions]messagebox.showinfo("成功", "條件已保存")except Exception as e:messagebox.showerror("錯誤", f"保存失敗:{str(e)}")def select_condition(self, event):"""選擇已保存的條件"""selected_name = self.condition_combo.get()for name, expr in self.saved_conditions:if name == selected_name:self.condition_entry.delete(0, tk.END)self.condition_entry.insert(0, expr)breakdef clear_condition(self):"""清空篩選條件和結果"""self.condition_entry.delete(0, tk.END)self.result_tree.delete(*self.result_tree.get_children())self.filtered_df = pd.DataFrame()messagebox.showinfo("已清空", "篩選條件和結果已重置")def __del__(self):"""關閉數據庫連接"""if hasattr(self, 'conn'):self.conn.close()if __name__ == "__main__":root = tk.Tk()app = ExcelViewerApp(root)root.geometry("1366x768")root.mainloop()
完畢!!感謝您的收看
----------★★跳轉到歷史博文集合★★----------
我的零基礎Python教程,Python入門篇 進階篇 視頻教程 Py安裝py項目 Python模塊 Python爬蟲 Json Xpath 正則表達式 Selenium Etree CssGui程序開發 Tkinter Pyqt5 列表元組字典數據可視化 matplotlib 詞云圖 Pyecharts 海龜畫圖 Pandas Bug處理 電腦小知識office自動化辦公 編程工具 NumPy Pygame