使用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()
相关推荐
m***记5 分钟前
Python 数据分析入门:Pandas vs NumPy 全方位对比
python·数据分析·pandas
MYX_30912 分钟前
第七章 完整的模型训练
pytorch·python·深度学习·学习
froginwe1117 分钟前
R 矩阵:解析与应用
开发语言
_OP_CHEN20 分钟前
C++基础:(十六)priority_queue和deque的深度解析
开发语言·c++
C++ 老炮儿的技术栈25 分钟前
include″″与includ<>的区别
c语言·开发语言·c++·算法·visual studio
Vallelonga25 分钟前
Rust 设计模式 Marker Trait + Blanket Implementation
开发语言·设计模式·rust
新子y29 分钟前
【小白笔记】岛屿数量
笔记·python
CHANG_THE_WORLD33 分钟前
PDFium导出pdf 图像
开发语言·c++·pdf
CLubiy35 分钟前
【研究生随笔】Pytorch中的线性代数
pytorch·python·深度学习·线性代数·机器学习
reasonsummer37 分钟前
【办公类-115-02】20251018信息员每周通讯上传之文字稿整理(PDF转docx没有成功)
python·pdf