使用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()
相关推荐
高山流水&上善21 小时前
基于Qwen3-0.6B的光纤基础测试问答系统设计与实现
python·django
Chase_______21 小时前
【JAVA基础指南(四)】快速掌握类和对象 基础篇
android·java·开发语言
每天吃饭的羊21 小时前
Node.js 创建可二次编辑的 HTML 文档并生成文件
开发语言·javascript·ecmascript
疯狂成瘾者21 小时前
PromptTemplate类解读
python·langchain
2501_9307077821 小时前
使用C#代码在 Excel 中创建数据透视图
excel
Cat_Rocky21 小时前
创建LNMRP后端技术栈
java·开发语言
牛马11121 小时前
Flutter BoxDecoration border 完整用法
开发语言·前端·javascript
kk在加油21 小时前
python学习笔记(基础语法与变量、容器)
笔记·python·学习
biter down21 小时前
STL list
开发语言·c++
xyq202421 小时前
R 绘图 - 函数曲线图
开发语言