注意:由于最新版本的xlrd(如2.0.1)不支持xlsx格式,可以通过卸载当前版本并安装一个较早的版本来解决问题,pip uninstall xlrd;pip install xlrd==1.2.0。另外装旧版本xlrd时如果报错的话,更改下python的版本,尽量选旧得;因为我用最新python编辑器装xlrd==1.2.0时,报错。
下面是具体的代码:
# 导入tkinter库
import tkinter as tk
import pandas as pd
import xlrd
from tkinter import filedialog
from xlwings import Sheet
"""
创建GUI窗口
Name:wsb
Time:2024/04/25
"""
""" alt+shift+a多行注释 """
"""
1、没有pandas依赖:
在命令行输入来导入pandas依赖包pip install pandas
To update,run:python.exe -m pip install --upgrade pip
2、xlrd库
由于最新版本的xlrd(如2.0.1)不支持xlsx格式,可以通过卸载当前版本并安装一个较早的版本来解决问题。具体操作为在命令行中执行以下命令:
pip uninstall xlrd
pip install xlrd==1.2.0
装旧版本的时候可能会出错。我不想改了,如果你想继续使用xlrd库的话,尝试着改下python的版本吧。
"""
# 创建GUI窗口
window = tk.Tk()
window.title("Excel展示")
#选择Excel文件
#获取想读取文件的绝对路径
def choose_file():
#弹出文件选择对话框
""" 使用choose_file()【自定义函数】{获取文件的路径名},并且调用read_excel()【自定义函数】} """
#使用askopenfilename()函数来打开文件选择对话框。这个函数允许用户从文件系统中选择一个文件,并返回选定文件的路径字符串
file_path = filedialog.askopenfilename()
print("Selected'file:",file_path)
#调用读取Excel数据的函数
read_excel(file_path)
#读取Excel数据
#在choose_file()中读取指定路径的Excel文件,然后读取该文件,并将读取到的内容写入到pandas的DataFrame中
def read_excel(file_path):
""" 使用read_excel()【自定义函数】{读取choose_file()函数选择的文件,将其存储到pandas的DateFrame中,然后调用show_excel_date()函数来展示Excel数据"""
#使用xlrd库读取Excel文件
excel_data = xlrd.open_workbook(file_path)
#xlrd.os
#获取Excel文件的第一个Sheet
Sheet = excel_data.sheet_by_index(0)
#将Sheet数据存储到pandas的DateFrame中
df = pd.DataFrame(Sheet.get_all_values())
#调用展示Excel数据的函数
show_excel_date(df)
#展示Excel数据
#在read_excel()函数里面获取读取的数据,并通过tkinter的Text组件来展示读取到数据
def show_excel_date(df):
#创建用于展示Excel数据的Text组件
text = tk.Text(window)
#将pandas的DataFrame转换为字符串
text.insert("1.0",df.to_string())
text.pack()
#创建选择文件按钮
button = tk.Button(window, text="选择Excel文件", command=choose_file)
button.pack()
#运行GUI窗口
window.mainloop()