pandas读取Excel数据(.xlsx和.xls)
Python,速成心法
敲代码,查资料 ,问 Ai
练习,探索,总结,优化
★ ★ ★ ★ ★ ★ ★ ★ ★ ★
Python教程:PyCharm安装过程中遇到的中英文对照表
Python教程110:单线程和多线程源码演示(threading)
Python教程108:针对面向对象Class类知识要点,源码示例再演示。
Python入门教程04:流程控制语句(if+for+continue等)
对于.xls文件,xlrd可能更合适,但需要注意新版本的xlrd可能不支持xlsx,不过用户可能同时需要处理两种格式,所以可能需要结合openpyxl和xlrd?或者 直接用pandas,因为它内部会处理这些依赖。
运行后的效果
↓ 完整源码如下 ↓
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
import pandas as pd
def load_excel_to_treeview():
file_path = filedialog.askopenfilename(
filetypes=[("Excel Files", "*.xlsx *.xls")]
)
if not file_path:
return
# 根据扩展名选择引擎
if file_path.endswith('.xlsx'):
engine = 'openpyxl'
elif file_path.endswith('.xls'):
engine = 'xlrd'
else:
return
try:
df = pd.read_excel(file_path, engine=engine)
except Exception as e:
print("读取文件失败:", e)
return
# 清空Treeview
for item in tree.get_children():
tree.delete(item)
# 设置列
tree["columns"] = list(df.columns)
tree["show"] = "headings"
# 配置列标题
for col in tree["columns"]:
tree.heading(col, text=col)
tree.column(col, width=70)
# 插入数据
for index, row in df.iterrows():
tree.insert("", "end", values=list(row))
# 创建主窗口
root = tk.Tk()
root.title("Excel数据查看器")
# 创建Treeview
tree = ttk.Treeview(root)
tree.pack(fill="both", expand=True)
# 添加按钮
btn = tk.Button(root, text="打开Excel文件", command=load_excel_to_treeview)
btn.pack(pady=10)
root.mainloop()
完毕!!感谢您的收看
------★ ★ ---- - -
Xpath 正则表达式 Selenium Etree Css