[PyQt5] Open Excel, CSV, convert tableWidget to dataframe, add options to listWidget, for loop list derivation–list/dict

untitled.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(640, 480)
        self.verticalLayout_3 = QtWidgets.QVBoxLayout(Form)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.pushButton_excel = QtWidgets.QPushButton(Form)
        self.pushButton_excel.setObjectName("pushButton_excel")
        self.horizontalLayout_2.addWidget(self.pushButton_excel)
        self.pushButton_csv = QtWidgets.QPushButton(Form)
        self.pushButton_csv.setObjectName("pushButton_csv")
        self.horizontalLayout_2.addWidget(self.pushButton_csv)
        self.verticalLayout_3.addLayout(self.horizontalLayout_2)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.tableWidget = QtWidgets.QTableWidget(Form)
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(0)
        self.tableWidget.setRowCount(0)
        self.verticalLayout_2.addWidget(self.tableWidget)
        self.pushButton_tW2df = QtWidgets.QPushButton(Form)
        self.pushButton_tW2df.setObjectName("pushButton_tW2df")
        self.verticalLayout_2.addWidget(self.pushButton_tW2df)
        self.horizontalLayout.addLayout(self.verticalLayout_2)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.listWidget = QtWidgets.QListWidget(Form)
        self.listWidget.setObjectName("listWidget")
        self.verticalLayout.addWidget(self.listWidget)
        self.pushButton_addLW = QtWidgets.QPushButton(Form)
        self.pushButton_addLW.setObjectName("pushButton_addLW")
        self.verticalLayout.addWidget(self.pushButton_addLW)
        self.pushButton_fL = QtWidgets.QPushButton(Form)
        self.pushButton_fL.setObjectName("pushButton_fL")
        self.verticalLayout.addWidget(self.pushButton_fL)
        self.pushButton_fD = QtWidgets.QPushButton(Form)
        self.pushButton_fD.setObjectName("pushButton_fD")
        self.verticalLayout.addWidget(self.pushButton_fD)
        self.horizontalLayout.addLayout(self.verticalLayout)
        self.horizontalLayout.setStretch(0, 3)
        self.horizontalLayout.setStretch(1, 1)
        self.verticalLayout_3.addLayout(self.horizontalLayout)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.pushButton_excel.setText(_translate("Form", "Open Excel"))
        self.pushButton_csv.setText(_translate("Form", "Open CSV"))
        self.pushButton_tW2df.setText(_translate("Form", "tableWidget converted to dataframe"))
        self.pushButton_addLW.setText(_translate("Form", "listWidget add option"))
        self.pushButton_fL.setText(_translate("Form", "for loop list comprehension --list"))
        self.pushButton_fD.setText(_translate("Form", "for loop list comprehension--dict"))

Main code:

import sys
import pandas as pd

from PyQt5.QtWidgets import *

from untitled import Ui_Form


class MyMainWindow(QWidget, Ui_Form): # Inherit the QWidget class and Ui_Form interface class

    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent) #Initialize the parent class
        self.setupUi(self) #Inherit Ui_Form interface class

        #Set the selection mode to multi-selection mode
        # self.listWidget.setSelectionMode(QListWidget.ExtendedSelection)
        self.listWidget.setSelectionMode(QAbstractItemView.MultiSelection)

        # ********** Open Excel
        self.pushButton_excel.clicked.connect(self.openExcel)
        self.pushButton_excel.clicked.connect(self.creatExcelTable)

        # ********** Open CSV
        self.pushButton_csv.clicked.connect(self.openCSV)
        self.pushButton_csv.clicked.connect(self.creatCsvTable)

        # ********** Convert tableWidget to dataframe
        self.pushButton_tW2df.clicked.connect(self.tW2df)

        # ********** Set up_listWidget options
        self.pushButton_addLW.clicked.connect(self.addlistWidgetItem)

        # ********** for loop list comprehension--list
        self.pushButton_fL.clicked.connect(self.forLoopListDerivationFormula_list)

        # ********** for loop list comprehension--dict
        self.pushButton_fD.clicked.connect(self.forLoopListDerivationFormula_dict)

    # Open Excel
    def openExcel(self):
        openXlsName = QFileDialog.getOpenFileName(self, 'Select Excel file', '',
                                                  'Excel files(*.xlsx, *.xls)')

        global excelPath

        excelPath = openXlsName[0]
        # print("Excel path:", excelPath)

    def creatExcelTable(self):
        # print("Excel path:", excelPath)
        try:
            # Read Excel and transfer the content into the table
            inputTable = pd.read_excel(excelPath)
            # print(inputTable)

            # Set the number of rows and columns in the table
            inputTableRows = inputTable.shape[0]
            inputTableColunms = inputTable.shape[1]
            # print(inputTableRows)
            # print(inputTableColunms)
            self.tableWidget.setRowCount(inputTableRows)
            self.tableWidget.setColumnCount(inputTableColunms)

            # Header settings
            inputTableHeader = inputTable.columns.values.tolist()
            # print(inputTableHeader)
            self.tableWidget.setHorizontalHeaderLabels(inputTableHeader)

            for i in range(inputTableRows):
                for j in range(inputTableColunms):
                    self.tableWidget.setItem(i, j, QTableWidgetItem(str(inputTable.iloc[i, j])))

            # Set the table to be non-editable
            self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)

        except Exception as e:
            QMessageBox.critical(self, "Error", f"An error occurred while reading the Excel file.\\
{e}")

    # Open CSV
    def openCSV(self):
        openCsvName = QFileDialog.getOpenFileName(self, 'Select CSV file', '',
                                                  'CSV files(*.csv)')

        global csvPath

        csvPath = openCsvName[0]
        # print("Csv path:", csvPath)

    def creatCsvTable(self):
        # print("Csv path:", csvPath)
        try:
            # Read CSV and transfer the content into a table
            inputTable = pd.read_csv(csvPath)
            # print(inputTable)

            # Set the number of rows and columns in the table
            inputTableRows = inputTable.shape[0]
            inputTableColunms = inputTable.shape[1]
            # print(inputTableRows)
            # print(inputTableColunms)
            self.tableWidget.setRowCount(inputTableRows)
            self.tableWidget.setColumnCount(inputTableColunms)

            # Header settings
            inputTableHeader = inputTable.columns.values.tolist()
            # print(inputTableHeader)
            self.tableWidget.setHorizontalHeaderLabels(inputTableHeader)

            for i in range(inputTableRows):
                for j in range(inputTableColunms):
                    self.tableWidget.setItem(i, j, QTableWidgetItem(str(inputTable.iloc[i, j])))

            # Set the table to be non-editable
            self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)

        except Exception as e:
            QMessageBox.critical(self, "Error", f"An error occurred while reading the CSV file. \\
{e}")

    def addlistWidgetItem(self):
        # Clear option box (required)
        self.listWidget.clear()

        # Return the number of table columns in the main window
        numberCol = self.tableWidget.columnCount()
        # print(numberCol)
        listWidgeDt = []
        # Get table header content
        for c in range(numberCol):
            headerItem = self.tableWidget.horizontalHeaderItem(c)
            # print(headerItem)
            if headerItem != None:
                headerText = headerItem.text()
                # print(headerText)
                listWidgeDt.append(headerText)
        # print(listWidgeDt)

        self.listWidget.addItems(listWidgeDt)
        self.listWidget.selectAll() # Set select all

    def tableWidget2dataframe(self, tableWidget):
        data = []
        for r in range(self.tableWidget.rowCount()):
            row = []
            for c in range(self.tableWidget.columnCount()):
                item = self.tableWidget.item(r, c)
                if item is not None:
                    row.append(item.text())
                else:
                    row.append('')
            data.append(row)
        df = pd.DataFrame(data)
        return df

    def tW2df(self):
        print(self.tableWidget2dataframe(self.tableWidget))

    def forLoopListDerivationFormula_list(self):
        # Get the selected text
        # selectItem = self.listWidget.currentItem() # Return the selected item (single selection only)
        selectItem = self.listWidget.selectedItems() # Return a list object containing item objects
        select_item = [i.text() for i in selectItem]
        # print(select_item)

        tb_cols = self.tableWidget.columnCount()
        #Method 1: for loop
        list_c = []
        for i in select_item:
            for c in range(tb_cols):
                if self.tableWidget.horizontalHeaderItem(c).text() == i:
                    # print(c)
                    list_c.append(c)
        print(list_c)
        #Method 2: for loop list comprehension
        list_x = [c for i in select_item for c in range(tb_cols) if
                  self.tableWidget.horizontalHeaderItem(c).text() == i]
        print(list_x)

    def forLoopListDerivationFormula_dict(self):
        # Get the selected text
        # selectItem = self.listWidget.currentItem() # Return the selected item (single selection only)
        selectItem = self.listWidget.selectedItems() # Return a list object containing item objects
        select_item = [i.text() for i in selectItem]
        # print(select_item)

        tb_cols = self.tableWidget.columnCount()
        dict_x = {c: i for i in select_item for c in range(tb_cols) if
                  self.tableWidget.horizontalHeaderItem(c).text() == i}
        print(dict_x)


if __name__ == '__main__':
    app = QApplication(sys.argv) # Used in the QApplication method to create the application object
    myWin = MyMainWindow() # Instantiate the MyMainWindow class and create the main window
    myWin.show() # Display the control on the desktop myWin
    sys.exit(app.exec_()) #End the process and exit the program