1.智能路徑處理:自動識別并修正文件擴展名,根據轉換類型自動建議目標路徑,實時路徑格式驗證,自動補全缺失的文件擴展名。
2.增強型預覽功能:使用pandastable庫實現表格預覽,第三方模塊自己安裝一下,自動加載前10行數據,支持實時預覽更新,自動調整列寬,SQLite表名自動檢測。
pip install pandastable
3.改進的UI交互:分欄式布局(左側控制/右側預覽),自動保存路徑建議,智能表名檢測(SQLite),實時錯誤反饋,一鍵清空預覽。
4.使用說明:選擇轉換類型,瀏覽選擇源文件(自動生成目標路徑建議),查看右側數據預覽確認數據正確性,(數據庫轉換需要輸入/選擇表名),點擊"開始轉換"按鈕
# -*- coding: utf-8 -*-
# @Author : 小紅牛
# 微信公眾號:WdPython
import os
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from tkinter.simpledialog import askstring
import sqlite3
import pandas as pd
from pandastable import Tableclass DataConverterApp:def __init__(self, root):self.root = rootself.root.title("智能數據轉換工具1.0")self.root.geometry("1200x700")# 初始化變量self.source_path = tk.StringVar()self.target_path = tk.StringVar()self.table_name = tk.StringVar()self.conversion_type = tk.StringVar(value="excel2json")# 文件類型映射self.file_extensions = {"excel": ("Excel文件", ".xlsx"),"json": ("JSON文件", ".json"),"csv": ("CSV文件", ".csv"),"sqlite": ("SQLite數據庫", ".db")}# 創建界面self.create_widgets()self.setup_preview_table()def setup_preview_table(self):"""初始化數據預覽表格"""self.preview_frame = ttk.Frame(self.preview_container)self.preview_frame.pack(fill=tk.BOTH, expand=True)self.ptable = Table(self.preview_frame, showtoolbar=False, showstatusbar=True)self.ptable.show()def create_widgets(self):# 主容器main_frame = ttk.Frame(self.root, padding=20)main_frame.pack(fill=tk.BOTH, expand=True)# 左側控制面板control_frame = ttk.Frame(main_frame, width=400)control_frame.pack(side=tk.LEFT, fill=tk.Y)# 右側預覽面板self.preview_container = ttk.LabelFrame(main_frame, text="數據預覽", padding=10)self.preview_container.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)# 轉換類型選擇type_frame = ttk.LabelFrame(control_frame, text="轉換類型", padding=10)type_frame.pack(fill=tk.X, pady=5)conversion_types = [("Excel → JSON", "excel2json"),("JSON → Excel", "json2excel"),("CSV → JSON", "csv2json"),("JSON → CSV", "json2csv"),("SQLite → Excel", "sqlite2excel"),("Excel → SQLite", "excel2sqlite"),("SQLite → CSV", "sqlite2csv"),("CSV → SQLite", "csv2sqlite")]for text, value in conversion_types:rb = ttk.Radiobutton(type_frame, text=text, variable=self.conversion_type,value=value, command=self.update_ui)rb.pack(anchor=tk.W, pady=2)# 源文件設置source_frame = ttk.LabelFrame(control_frame, text="源文件設置", padding=10)source_frame.pack(fill=tk.X, pady=5)ttk.Label(source_frame, text="源文件路徑:").pack(anchor=tk.W)ttk.Entry(source_frame, textvariable=self.source_path, width=50).pack(side=tk.LEFT, fill=tk.X, expand=True)ttk.Button(source_frame, text="瀏覽...", command=self.browse_source).pack(side=tk.RIGHT)# 目標文件設置target_frame = ttk.LabelFrame(control_frame, text="目標設置", padding=10)target_frame.pack(fill=tk.X, pady=5)ttk.Label(target_frame, text="目標路徑:").pack(anchor=tk.W)ttk.Entry(target_frame, textvariable=self.target_path, width=50).pack(side=tk.LEFT, fill=tk.X, expand=True)ttk.Button(target_frame, text="瀏覽...", command=self.browse_target).pack(side=tk.RIGHT)# 數據庫表名設置self.table_frame = ttk.LabelFrame(control_frame, text="數據庫設置", padding=10)ttk.Label(self.table_frame, text="表名:").pack(side=tk.LEFT)ttk.Entry(self.table_frame, textvariable=self.table_name).pack(side=tk.LEFT, fill=tk.X, expand=True)# 操作按鈕btn_frame = ttk.Frame(control_frame)btn_frame.pack(fill=tk.X, pady=10)ttk.Button(btn_frame, text="開始轉換", command=self.start_conversion).pack(side=tk.LEFT, padx=5)ttk.Button(btn_frame, text="清空預覽", command=self.clear_preview).pack(side=tk.LEFT, padx=5)ttk.Button(btn_frame, text="退出", command=self.root.quit).pack(side=tk.RIGHT, padx=5)# 綁定路徑變化事件self.source_path.trace_add("write", self.update_preview)self.table_name.trace_add("write", self.update_preview)self.update_ui()def get_conversion_info(self):"""獲取當前轉換類型信息"""ct = self.conversion_type.get()source_type = ct.split("2")[0]target_type = ct.split("2")[1]return source_type, target_typedef update_ui(self):"""更新界面元素"""source_type, target_type = self.get_conversion_info()# 更新數據庫設置可見性if "sqlite" in self.conversion_type.get():self.table_frame.pack(fill=tk.X, pady=5)else:self.table_frame.pack_forget()# 自動更新目標路徑后綴current_target = self.target_path.get()if current_target:base, _ = os.path.splitext(current_target)new_ext = self.file_extensions[target_type][1]self.target_path.set(f"{base}{new_ext}")def browse_source(self):"""選擇源文件"""source_type, _ = self.get_conversion_info()file_type = self.file_extensions[source_type]path = filedialog.askopenfilename(title="選擇源文件",filetypes=[file_type, ("所有文件", "*.*")])if path:self.source_path.set(path)self.auto_suggest_target_path(path)def auto_suggest_target_path(self, source_path):"""自動生成目標路徑建議"""source_type, target_type = self.get_conversion_info()base = os.path.splitext(source_path)[0]new_ext = self.file_extensions[target_type][1]suggested_path = f"{base}_converted{new_ext}"self.target_path.set(suggested_path)def browse_target(self):"""選擇目標路徑"""_, target_type = self.get_conversion_info()file_type = self.file_extensions[target_type]path = filedialog.asksaveasfilename(title="保存目標文件",defaultextension=file_type[1],filetypes=[file_type, ("所有文件", "*.*")])if path:self.target_path.set(path)def clear_preview(self):"""清空預覽"""self.ptable.clearTable()self.ptable.model.df = pd.DataFrame()self.ptable.redraw()def load_preview_data(self):"""加載預覽數據"""source_path = self.source_path.get()if not source_path:return Nonetry:source_type, _ = self.get_conversion_info()if source_type == "excel":return pd.read_excel(source_path, nrows=10)elif source_type == "csv":return pd.read_csv(source_path, nrows=10)elif source_type == "json":return pd.read_json(source_path).head(10)elif source_type == "sqlite":conn = sqlite3.connect(source_path)table_name = self.table_name.get() or self.detect_table_name(conn)if table_name:return pd.read_sql_query(f"SELECT * FROM {table_name} LIMIT 10", conn)return Noneexcept Exception as e:messagebox.showerror("預覽錯誤", f"無法加載數據: {str(e)}")return Nonedef detect_table_name(self, conn):"""自動檢測數據庫表名"""cursor = conn.cursor()cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")tables = cursor.fetchall()if tables:return askstring("選擇表", "檢測到多個表,請選擇:", initialvalue=tables[0][0])return Nonedef update_preview(self, *args):"""更新數據預覽"""df = self.load_preview_data()if df is not None:self.ptable.model.df = dfself.ptable.redraw()self.ptable.autoResizeColumns()def start_conversion(self):"""執行轉換操作"""source_path = self.source_path.get()target_path = self.target_path.get()conversion_type = self.conversion_type.get()table_name = self.table_name.get()try:# 自動修正目標路徑后綴_, target_type = self.get_conversion_info()target_ext = self.file_extensions[target_type][1]if not target_path.endswith(target_ext):target_path = f"{os.path.splitext(target_path)[0]}{target_ext}"self.target_path.set(target_path)# 執行轉換邏輯if conversion_type == "excel2json":df = pd.read_excel(source_path)df.to_json(target_path, orient='records', indent=4)elif conversion_type == "json2excel":df = pd.read_json(source_path)df.to_excel(target_path, index=False)elif conversion_type == "csv2json":df = pd.read_csv(source_path)df.to_json(target_path, orient='records', indent=4)elif conversion_type == "json2csv":df = pd.read_json(source_path)df.to_csv(target_path, index=False)elif conversion_type == "sqlite2excel":conn = sqlite3.connect(source_path)table_name = table_name or self.detect_table_name(conn)df = pd.read_sql_query(f"SELECT * FROM {table_name}", conn)df.to_excel(target_path, index=False)elif conversion_type == "excel2sqlite":df = pd.read_excel(source_path)conn = sqlite3.connect(target_path)df.to_sql(table_name or "Sheet1", conn, if_exists='replace', index=False)elif conversion_type == "sqlite2csv":conn = sqlite3.connect(source_path)table_name = table_name or self.detect_table_name(conn)df = pd.read_sql_query(f"SELECT * FROM {table_name}", conn)df.to_csv(target_path, index=False)elif conversion_type == "csv2sqlite":df = pd.read_csv(source_path)conn = sqlite3.connect(target_path)df.to_sql(table_name or "CSV_Data", conn, if_exists='replace', index=False)messagebox.showinfo("成功", f"文件已成功保存到:\n{target_path}")self.update_preview()except Exception as e:messagebox.showerror("錯誤", f"轉換失敗: {str(e)}")if __name__ == "__main__":root = tk.Tk()app = DataConverterApp(root)root.mainloop()
完畢!!感謝您的收看
----------★★跳轉到歷史博文集合★★----------
我的零基礎Python教程,Python入門篇 進階篇 視頻教程 Py安裝py項目 Python模塊 Python爬蟲 Json Xpath 正則表達式 Selenium Etree CssGui程序開發 Tkinter Pyqt5 列表元組字典數據可視化 matplotlib 詞云圖 Pyecharts 海龜畫圖 Pandas Bug處理 電腦小知識office自動化辦公 編程工具 NumPy Pygame