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

实现用户选择Excel工作簿及工作表转换为Pandas DataFrame

实现方案

你写的代码硬编码了sheet_name=1,自然没法支持用户选工作表。改的时候按这个逻辑走就行:

  • 弹文件选择框让用户选本地Excel,记得判断用户有没有点取消,别拿到空路径直接跑报错
  • 别上来就读文件内容,先用pd.ExcelFile打开文件,拿sheet_names属性拿到所有工作表名,这步几乎不占内存,速度很快
  • 判断工作表数量:
    • 只有1个的话直接读第一个,不用弹额外窗口
    • 多于1个就弹个简单的列表选择窗,把所有工作表名列出来让用户选,选完再读对应的表

完整代码

import pandas as pd
import tkinter as tk
from tkinter import filedialog, ttk

def _sheet_select_popup(sheet_list):
    selected_val = []
    pop_win = tk.Toplevel()
    pop_win.title("选择工作表")
    pop_win.geometry("320x280")

    # 工作表列表,单选模式
    lb = tk.Listbox(pop_win, selectmode=tk.SINGLE)
    for idx, name in enumerate(sheet_list):
        lb.insert(idx, name)
    lb.selection_set(0)  # 默认选中第一个,减少用户操作
    lb.pack(pady=15, padx=20, fill=tk.BOTH, expand=True)

    def _confirm():
        sel_idx = lb.curselection()
        if sel_idx:
            selected_val.append(sheet_list[sel_idx[0]])
        pop_win.destroy()

    ttk.Button(pop_win, text="确认加载", command=_confirm).pack(pady=10)
    pop_win.grab_set()
    pop_win.wait_window()
    return selected_val[0] if selected_val else None

# 初始化tk,隐藏主窗口
root = tk.Tk()
root.withdraw()

# 选文件,加Excel文件格式过滤
file_path = filedialog.askopenfilename(
    title="选择Excel文件",
    filetypes=[("Excel文件", "*.xlsx *.xls *.xlsm")]
)
if not file_path:
    exit("未选择文件,程序退出")

# 读取所有工作表名称
xls_handler = pd.ExcelFile(file_path)
all_sheets = xls_handler.sheet_names

if len(all_sheets) == 1:
    target_sheet = all_sheets[0]
else:
    target_sheet = _sheet_select_popup(all_sheets)
    if not target_sheet:
        exit("未选择工作表,程序退出")

# 加载目标工作表为DataFrame
df = pd.read_excel(xls_handler, sheet_name=target_sheet)

说明

  • 全程复用同一个ExcelFile对象,不需要重复打开文件,加载速度更快
  • 文件选择框加了格式过滤,避免用户误选非Excel类型文件
  • 单工作表场景全程无额外弹窗,多工作表场景默认选中第一个表,操作成本低
  • 所有用户点击取消的分支都做了判断,不会抛出空路径类的无意义报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 18:48:24