You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python Tkinter实现用户选择的Excel文件导入MySQL数据库

实现Tkinter GUI选择Excel文件并导入MySQL

1. 安装必要依赖

先安装所需的Python库:

pip install pandas mysql-connector-python openpyxl

注:tkinter一般随Python默认安装,若缺失可自行通过包管理器安装。

2. 完整实现代码

以下是可直接运行的完整代码,包含文件选择、Excel读取、MySQL导入全流程:

import tkinter as tk
from tkinter import filedialog, messagebox
import pandas as pd
import mysql.connector
from mysql.connector import Error

def select_excel_file():
    # 创建隐藏的Tk主窗口,仅显示文件选择对话框
    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.askopenfilename(
        title="选择Excel文件",
        filetypes=[("Excel 2007+ 文件", "*.xlsx"), ("所有文件", "*.*")]
    )
    return file_path

def read_excel_data(file_path):
    try:
        # 读取Excel,默认用第一行作为表头
        df = pd.read_excel(file_path, engine='openpyxl')
        return df
    except Exception as e:
        messagebox.showerror("读取失败", f"Excel文件读取错误:{str(e)}")
        return None

def import_to_mysql(df, db_config, table_name):
    try:
        # 建立MySQL连接
        conn = mysql.connector.connect(**db_config)
        if not conn.is_connected():
            raise Error("无法连接到MySQL数据库")
        
        cursor = conn.cursor()
        
        # 自动生成表结构(简单数据类型映射)
        def map_dtype_to_sql(pd_dtype):
            if pd.api.types.is_integer_dtype(pd_dtype):
                return "INT"
            elif pd.api.types.is_float_dtype(pd_dtype):
                return "FLOAT"
            elif pd.api.types.is_datetime64_dtype(pd_dtype):
                return "DATETIME"
            else:
                return "VARCHAR(255)"
        
        # 拼接建表SQL
        column_defs = ", ".join([f"`{col}` {map_dtype_to_sql(df[col].dtype)}" for col in df.columns])
        create_table_sql = f"CREATE TABLE IF NOT EXISTS `{table_name}` ({column_defs})"
        cursor.execute(create_table_sql)
        
        # 拼接批量插入SQL
        placeholders = ", ".join(["%s"] * len(df.columns))
        insert_sql = f"INSERT INTO `{table_name}` ({', '.join([f'`{col}`' for col in df.columns])}) VALUES ({placeholders})"
        
        # 转换DataFrame为元组列表,适配MySQL插入格式
        data_rows = [tuple(row) for row in df.values]
        
        # 批量插入数据
        cursor.executemany(insert_sql, data_rows)
        conn.commit()
        messagebox.showinfo("导入成功", f"已成功导入 {cursor.rowcount} 条数据到表 {table_name}")
        
    except Error as e:
        messagebox.showerror("数据库错误", f"MySQL操作失败:{str(e)}")
        if conn:
            conn.rollback()
    finally:
        # 关闭数据库连接
        if conn and conn.is_connected():
            cursor.close()
            conn.close()

def main():
    # MySQL连接配置,可改为GUI输入框让用户填写
    db_config = {
        "host": "localhost",
        "user": "你的MySQL用户名",
        "password": "你的MySQL密码",
        "database": "目标数据库名"
    }
    target_table = "imported_excel_data"  # 可改为用户输入的表名
    
    # 选择Excel文件
    file_path = select_excel_file()
    if not file_path:
        return
    
    # 读取Excel数据
    df = read_excel_data(file_path)
    if df is None:
        return
    
    # 导入到MySQL
    import_to_mysql(df, db_config, target_table)

if __name__ == "__main__":
    main()

3. 关键优化与注意事项

  • 数据库配置优化:可在GUI中添加输入框让用户填写MySQL连接信息,避免硬编码。
  • 数据类型映射:示例中的类型映射是基础版,若需支持长文本、大整数等,可扩展map_dtype_to_sql函数,比如将长文本映射为TEXT,大整数映射为BIGINT。
  • 表头规范:确保Excel第一行是合法的字段名,避免MySQL关键字(如date、user),若需使用需用反引号包裹。
  • 大数据量处理:若Excel数据量极大,可分批次插入,避免内存溢出。
  • GUI交互增强:可添加进度条显示导入进度,提升用户体验。

内容的提问来源于stack exchange,提问作者Samy Moustafa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:35:22