import sys
import pandas as pd
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox, QTableWidgetItem, QHeaderView, \
QAbstractItemView
from PyQt5.uic import loadUi
class FileRead(QMainWindow):
def __init__(self):
super(FileRead, self).__init__()
loadUi("FileRead.ui", self)
self.file_path = ""
self.pushButton.clicked.connect(self.browse_file)
self.pushButton_2.clicked.connect(self.read_excel)
def browse_file(self):
"""
Open a file dialog to browse Excel files.
"""
# QFileDialog.move(10 ,10);
file_name, _ = QFileDialog.getOpenFileName(self, "选择Excel文件", "", "Excel Files (*.xlsx)")
if file_name:
self.file_path = file_name
# print(self.file_path)
self.lineEdit.setText(self.file_path)
def read_excel(self):
"""
Read the Excel file using Pandas and display the data in the table widget.
"""
if not self.file_path:
QMessageBox.critical(self, "Error", "请选择一个Excel文件.")
return
try:
# print(self.file_path)
self.df = pd.read_excel(self.file_path)
#print(self.df.columns)
self.tableWidget.setRowCount(self.df.shape[0])
self.tableWidget.setColumnCount(self.df.shape[1])
# print(self.df.columns)
self.tableWidget.setHorizontalHeaderLabels(self.df.columns)
# 设置表头可伸缩模式
self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
# 设置表格为只读模式
self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
# print(self.df.shape[1])
for i in range(self.df.shape[0]):
for j in range(self.df.shape[1]):
tmp = str(self.df.iloc[i,j])
if tmp == "nan":
tmp=""
# print(tmp)
self.tableWidget.setItem(i, j, QTableWidgetItem(tmp))
except Exception as e:
print(e)
QMessageBox.critical(self, "Error", f"读取文件错误.\n\n{e}")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = FileRead()
window.show()
# setLayout(window)
sys.exit(app.exec_())
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
pythonProject.zip (2个子文件)
fileRead.py 2KB
FileRead.ui 5KB
共 2 条
- 1
资源评论
weixin_44706643
- 粉丝: 0
- 资源: 1
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功