- 作者:老汪软件技巧
- 发表时间:2024-01-04 09:00
- 浏览量:
pip ;
pip ;
pip pyqt5-tools;
编写.py 如下
# -*- coding: utf-8 -*-
""" pandas 读取 Excel文件或 .etx 电子表格文件,显示在 QTableWidget 中 """
import os
import sys
import numpy as np
import pandas as pd
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem
from PyQt5.uic import loadUi
class EtxReader(QMainWindow):
def __init__(self):
super(EtxReader, self).__init__()
loadUi("readEtx.ui", self) # Load the UI file
self.file_path = "" # To store the file path
self.df = pd.DataFrame() # To store the etx data
self.browse_btn.clicked.connect(self.browse_file)
self.read_btn.clicked.connect(self.read_etx)
def browse_file(self):
""" Open a file dialog to browse .etx file
"""
file_name, _ = QFileDialog.getOpenFileName(self, "Open etx File", "",
"xlsx File(*.xlsx);;etx File(*.etx)")
if file_name:
self.file_path = file_name
self.file_path_line_edit.setText(self.file_path)
def read_etx(self):
""" Read .etx file using Pandas and display the data in the table widget.
"""
if not self.file_path:
QMessageBox.critical(self, "Error", "Please select an etx file to read.")
return
try:
self.df = pd.read_excel(self.file_path)
self.table_widget.setRowCount(self.df.shape[0])
self.table_widget.setColumnCount(self.df.shape[1])
self.table_widget.setHorizontalHeaderLabels(map(str, self.df.columns))
#print(list(map(str, self.df.columns)))
print('shape:', self.df.shape)
for i in range(self.df.shape[0]):
for j in range(self.df.shape[1]):
v = self.df.iloc[i, j]
#print(type(v), v)
if (v is None) or (v is np.nan):
item = QTableWidgetItem('')
elif type(v) is str:
item = QTableWidgetItem(v)
elif type(v) is int or type(v) is np.int64:
item = QTableWidgetItem("%d" %v)
elif type(v) is float or type(v) is np.float64:
item = QTableWidgetItem("%.4f" %v)
else:
#print(type(v), v)
item = QTableWidgetItem(str(v))
self.table_widget.setItem(i, j, item)
except Exception as e:
QMessageBox.critical(self, "Error", f"Error: {e}")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = EtxReader()
window.show()
sys.exit(app.exec_())
编写 .ui 如下
ExcelReader
0
0
800
600
Excel Reader
10
20
111
16
Excel File:
110
20
431
22
true
570
20
75
23
Browse
670
20
75
23
Read
10
60
781
501
0
0
800
26
运行 .py
上一个线性代数中涉及到的命令-第二章:矩阵及其运算
下一个考研人考研魂——英语单词篇()
相关文章
管理员
元风软件技巧专注于操作系统、办公软件以及手机应用等的技巧方法分享,致力于不断提交软件爱好者的学习和工作效率。
热门文章