使用tkinter拖入excel文件并显示

使用tkinter拖入excel文件并显示

  • 效果
  • 代码

效果

代码

python 复制代码
import tkinter as tk
from tkinter import ttk
from tkinterdnd2 import TkinterDnD, DND_FILES
import pandas as pd


class ExcelViewerApp(TkinterDnD.Tk):
    def __init__(self):
        super().__init__()
        self.title("Excel Viewer")
        self.geometry("800x600")

        self.drop_label = ttk.Label(self, text="Drag and drop an Excel file here")
        self.drop_label.pack(pady=20)

        self.tree = ttk.Treeview(self)
        self.tree.pack(expand=True, fill='both')

        self.drop_target_register(DND_FILES)
        self.dnd_bind('<<Drop>>', self.drop)

    def drop(self, event):
        file_path = event.data.strip('{}')
        if file_path.endswith(('.xls', '.xlsx')):
            self.show_excel(file_path)
        else:
            self.drop_label.config(text="Please drop a valid Excel file")

    def show_excel(self, file_path):
        df = pd.read_excel(file_path)
        self.tree.delete(*self.tree.get_children())
        self.tree["columns"] = list(df.columns)
        self.tree["show"] = "headings"

        for column in self.tree["columns"]:
            self.tree.heading(column, text=column)

        for index, row in df.iterrows():
            self.tree.insert("", "end", values=list(row))

        self.drop_label.config(text="Drag and drop an Excel file here")


if __name__ == "__main__":
    app = ExcelViewerApp()
    app.mainloop()
相关推荐
奋斗吧程序媛几秒前
CSV文件导入功能
开发语言·javascript·ecmascript
evans在进步13 分钟前
Java 常用设计模式(二):装饰器、适配器、责任链、模板方法、策略与观察者
java·开发语言·设计模式
kyrie_sakura38 分钟前
python学习笔记11 -- 进程和线程
笔记·python·学习
小雨笙笙42 分钟前
C语言:指针
c语言·开发语言
Jialu.1 小时前
中文 NLP 模型部署实战:FastAPI 接口 + Streamlit 看板
人工智能·python·自然语言处理·fastapi
旧梦95271 小时前
Java EnumMap 详解:原理、用法与实战
java·开发语言
snow@li2 小时前
Java:微服务项目与单体项目区别、市场占有率全景深度分析
java·开发语言·微服务
Asum1ta2 小时前
K8s 学习环境搭建:Python 与 PyCharm 开发环境配置指南
python·学习·kubernetes
知识汲取者2 小时前
FastAPI 学习教程(写给想学 FastAPI 的 Java 工程师的)
python·学习·fastapi