123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348 |
- from ui import Ui_MainWindow
- from PyQt5 import QtCore, QtGui, QtWidgets
- import platform
- from icopy2xls import Mover
- import os
- import xlrd
- from icopy2xls.FilesOpen import FilesOpen
- import json
- from time import sleep
- class MainWindow(Ui_MainWindow):
- """ BaangtUI : Logic implementation file for uidesign
- """
- switch_window = QtCore.pyqtSignal(str)
- def __init__(self):
- ''' Init the super class '''
- super().__init__()
- def setupUi(self, MainWindow, directory=None):
- ''' Setup the UI for super class and Implement the
- logic here we want to do with User Interface
- '''
- super().setupUi(MainWindow)
- self.row_list = []
- self.filters = {}
- self.sheet_headers = []
- self.sourceFiles = []
- self.sourceBrowsePushButton.clicked.connect(self.sourceBrowsePathSlot)
- self.destinationBrowsePushButton.clicked.connect(self.destinationBrowsePathSlot)
- self.filterButton.clicked.connect(self.filterDialog)
- self.runButton.clicked.connect(self.runMain)
- self.openResultFilePushButton.clicked.connect(self.openResultFile)
- self.loadJsonFile()
- def sourceBrowsePathSlot(self):
- """ Browse Folder Containing *.xlsx file for execution. And
- globals.json file for Test specific settings
- """
- # get path from pathLineEdit
- basepath = self.sourcePathLineEdit.text()
- if not basepath:
- basepath = "./"
- options = QtWidgets.QFileDialog.Options()
- options |= QtWidgets.QFileDialog.DontUseNativeDialog
- dirName = QtWidgets.QFileDialog.getOpenFileNames(
- None,
- "Select File ",
- basepath,
- options=options,
- filter="Excel (*.xlsx *.xls)"
- )
- if dirName:
- # self.pathLineEdit.insert(dirName)
- self.setupBasePath(dirName, "source")
- def destinationBrowsePathSlot(self):
- """ Browse Folder Containing *.xlsx file for execution. And
- globals.json file for Test specific settings
- """
- # get path from pathLineEdit
- basepath = self.destinationPathLineEdit.text()
- if not basepath:
- basepath = "./"
- options = QtWidgets.QFileDialog.Options()
- options |= QtWidgets.QFileDialog.DontUseNativeDialog
- dirName = QtWidgets.QFileDialog.getOpenFileName(
- None,
- "Select File ",
- basepath,
- options=options,
- filter="Excel (*.xlsx *.xls)"
- )
- if dirName:
- # self.pathLineEdit.insert(dirName)
- self.setupBasePath(dirName, "destination")
- def setupBasePath(self, dirPath="", typ=""):
- """ Setup Base path of Execution as per directory Path"""
- if not dirPath:
- # Set up base path to Baangt directory
- # Based on current File path ../../../
- dirPath = os.path.dirname(os.path.dirname(
- os.path.dirname(os.path.dirname(__file__))
- ))
- if not dirPath:
- dirPath = os.path.abspath(os.curdir)
- if typ == "source":
- self.sourcePathLineEdit.insert(dirPath)
- self.sourceFiles = dirPath
- else:
- self.destinationPathLineEdit.insert(dirPath)
- else:
- if typ == "source":
- self.sourcePathLineEdit.setText(", ".join(dirPath[0]))
- self.sourceFiles = dirPath[0]
- else:
- self.destinationPathLineEdit.setText(dirPath[0])
- self.statusbar.showMessage(f"Current {typ} Path: {dirPath} ", 2000)
- if typ == "source":
- self.getSheetsSource(dirPath[0][0])
- else:
- self.getSheetsDestination(dirPath[0])
- def getSheetsSource(self, dirName):
- """ Scan for *.xlsx files and *.json files and
- update the testRunComboBox and settingsComboBox items
- """
- wb = xlrd.open_workbook(dirName)
- Sheets = wb.sheet_names()
- self.sourceSheetComboBox.clear()
- # Add files in Combo Box
- self.sourceSheetComboBox.addItems(Sheets)
- # set default selection to 0
- if len(Sheets) > 0:
- self.sourceSheetComboBox.setCurrentIndex(0)
- selectedSheet = self.sourceSheetComboBox.currentText()
- self.statusbar.showMessage("Sheet: {}".format(selectedSheet), 3000)
- def getSheetsDestination(self, dirName):
- """ Scan for *.xlsx files and *.json files and
- update the testRunComboBox and settingsComboBox items
- """
- wb = xlrd.open_workbook(dirName)
- Sheets = wb.sheet_names()
- self.destinationSheetComboBox.clear()
- # Add files in Combo Box
- self.destinationSheetComboBox.addItems(Sheets)
- # set default selection to 0
- if len(Sheets) > 0:
- self.destinationSheetComboBox.setCurrentIndex(0)
- selectedSheet = self.destinationSheetComboBox.currentText()
- self.statusbar.showMessage("Sheet: {}".format(selectedSheet), 3000)
- def filterDialog(self):
- self.row_list = []
- self.update_headers()
- self.filter_dialog = QtWidgets.QDialog(self.centralwidget)
- self.filter_dialog.setWindowTitle("Filters")
- self.vlay = QtWidgets.QVBoxLayout()
- hori = QtWidgets.QHBoxLayout()
- hori.setSpacing(10)
- add_button = QtWidgets.QPushButton("Add", self.filter_dialog)
- add_button.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(114, 159, 207);")
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
- sizePolicy.setHorizontalStretch(0)
- sizePolicy.setVerticalStretch(0)
- sizePolicy.setHeightForWidth(add_button.sizePolicy().hasHeightForWidth())
- add_button.setSizePolicy(sizePolicy)
- save_button = QtWidgets.QPushButton("Save", self.filter_dialog)
- save_button.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(138, 226, 52);")
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
- sizePolicy.setHorizontalStretch(0)
- sizePolicy.setVerticalStretch(0)
- sizePolicy.setHeightForWidth(save_button.sizePolicy().hasHeightForWidth())
- save_button.setSizePolicy(sizePolicy)
- hori.addWidget(add_button)
- hori.addWidget(save_button)
- self.vlay.addLayout(hori)
- self.filter_dialog.setLayout(self.vlay)
- add_button.clicked.connect(self.add_row)
- save_button.clicked.connect(self.save_filters)
- for data in self.filters:
- if not data:
- continue
- self.update_filterDialog(data, self.filters[data])
- self.filter_dialog.exec_()
- def update_headers(self):
- source_file = self.sourceFiles
- if isinstance(source_file, list):
- source_file = source_file[0]
- if source_file:
- wb = xlrd.open_workbook(source_file)
- sht = wb.sheet_by_name(self.sourceSheetComboBox.currentText())
- self.sheet_headers = [s.value for s in sht.row(0)]
- def update_filterDialog(self, key, value):
- for val in value:
- hr = QtWidgets.QHBoxLayout()
- hr.setSpacing(10)
- cb = QtWidgets.QComboBox()
- cb.setMinimumSize(QtCore.QSize(200, 0))
- cb.setMaximumSize(QtCore.QSize(250, 16777215))
- cb.setStyleSheet("background-color: rgb(255, 255, 255);")
- line = QtWidgets.QLineEdit()
- line.setMinimumSize(QtCore.QSize(300, 0))
- line.setMaximumSize(QtCore.QSize(350, 16777215))
- line.setStyleSheet("background-color: rgb(255, 255, 255);")
- cb.addItems(self.sheet_headers)
- cb.setCurrentIndex(self.sheet_headers.index(key))
- line.setText(val)
- hr.addWidget(cb)
- hr.addWidget(line)
- removeButton = QtWidgets.QPushButton()
- removeButton.setText("-")
- removeButton.clicked.connect(lambda: self.remove_row([cb, line, hr, removeButton]))
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
- sizePolicy.setHorizontalStretch(0)
- sizePolicy.setVerticalStretch(0)
- sizePolicy.setHeightForWidth(self.mainGroupBox.sizePolicy().hasHeightForWidth())
- removeButton.setSizePolicy(sizePolicy)
- hr.addWidget(removeButton)
- self.vlay.addLayout(hr)
- self.row_list.append([cb, line, hr, removeButton])
- def add_row(self):
- hr = QtWidgets.QHBoxLayout()
- hr.setSpacing(10)
- cb = QtWidgets.QComboBox()
- cb.setMinimumSize(QtCore.QSize(200, 0))
- cb.setMaximumSize(QtCore.QSize(250, 16777215))
- cb.setStyleSheet("background-color: rgb(255, 255, 255);")
- cb.addItems(self.sheet_headers)
- line = QtWidgets.QLineEdit()
- line.setMinimumSize(QtCore.QSize(300, 0))
- line.setMaximumSize(QtCore.QSize(350, 16777215))
- line.setStyleSheet("background-color: rgb(255, 255, 255);")
- hr.addWidget(cb)
- hr.addWidget(line)
- removeButton = QtWidgets.QPushButton()
- removeButton.setText("-")
- removeButton.clicked.connect(lambda: self.remove_row([cb, line, hr, removeButton]))
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
- sizePolicy.setHorizontalStretch(0)
- sizePolicy.setVerticalStretch(0)
- sizePolicy.setHeightForWidth(self.mainGroupBox.sizePolicy().hasHeightForWidth())
- removeButton.setSizePolicy(sizePolicy)
- hr.addWidget(removeButton)
- self.vlay.addLayout(hr)
- self.row_list.append([cb, line, hr, removeButton])
- def remove_row(self, last):
- key = last[0].currentText()
- if key in self.filters:
- self.filters[key].remove(last[1].text())
- if not self.filters[key]:
- del self.filters[key]
- for l in last:
- l.deleteLater()
- if last in self.row_list:
- self.row_list.remove(last)
- def save_filters(self):
- filters = {}
- if self.row_list:
- for row in self.row_list:
- key = row[0].currentText()
- if key not in filters:
- filters[key] = [row[1].text()]
- else:
- filters[key].append(row[1].text())
- self.filters = filters
- self.filter_dialog.close()
- def runMain(self):
- source, source_sheet, destination, destination_sheet = self.check_fields()
- if not source and not source_sheet and not destination and not destination_sheet:
- pass
- else:
- self.statusbar.showMessage("Running...", 3000)
- lines = self.linesInput.text()
- mover = Mover(source, source_sheet, destination, destination_sheet, lines)
- mover.move(self.filters, self.addMissingCheckBox.isChecked())
- self.statusbar.showMessage("Completed...", 3000)
- self.saveJsonFile(
- source, source_sheet, destination, destination_sheet,
- lines, self.filters, self.addMissingCheckBox.isChecked()
- )
- def check_fields(self):
- source = self.sourceFiles
- source_sheet = self.sourceSheetComboBox.currentText()
- destination = self.destinationPathLineEdit.text()
- destination_sheet = self.destinationSheetComboBox.currentText()
- if not source:
- self.statusbar.showMessage(f"Source file path is invalid! Please check", 5000)
- elif not source_sheet:
- self.statusbar.showMessage(f"Source sheet name is invalid! Please check", 5000)
- elif not destination:
- self.statusbar.showMessage(f"Destination file path is invalid! Please check", 5000)
- elif not destination_sheet:
- self.statusbar.showMessage(f"Destination sheet name is invalid! Please check", 5000)
- return source, source_sheet, destination, destination_sheet
- def openResultFile(self):
- destinationFile = self.destinationPathLineEdit.text()
- if destinationFile:
- if os.path.exists(destinationFile):
- FilesOpen.openResultFile(destinationFile)
- else:
- self.statusbar.showMessage(f"File doesn't exist : {destinationFile}")
- else:
- self.statusbar.showMessage(f"No destination File selected")
- def saveJsonFile(self, source, source_sht, dest, dest_sht, lines, filters, addMissing):
- path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "settings.json")
- js = {"source": source, "source_sheet": source_sht,
- "destination": dest, "destination_sheet": dest_sht,
- "lines": lines, "filters": filters, "addMissingColumn": addMissing}
- with open(path, 'w') as file:
- file.write(json.dumps(js))
- def loadJsonFile(self):
- path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "settings.json")
- if not os.path.exists(path):
- return
- js = json.load(open(path))
- self.sourceFiles = js["source"]
- self.sourcePathLineEdit.setText(", ".join(self.sourceFiles))
- self.getSheetsSource(self.sourceFiles[0])
- index_source = self.sourceSheetComboBox.findText(js["source_sheet"], QtCore.Qt.MatchFixedString)
- if index_source >= 0:
- self.sourceSheetComboBox.setCurrentIndex(index_source)
- self.destinationPathLineEdit.setText(js["destination"])
- self.getSheetsDestination(js["destination"])
- index_destination = self.destinationSheetComboBox.findText(js["destination_sheet"], QtCore.Qt.MatchFixedString)
- if index_destination >= 0:
- self.destinationSheetComboBox.setCurrentIndex(index_destination)
- self.linesInput.setText(js["lines"])
- self.filters = js["filters"]
- self.addMissingCheckBox.setChecked(js["addMissingColumn"])
- class MainController:
- def __init__(self):
- self.widget = QtWidgets.QWidget()
- self.window = QtWidgets.QMainWindow()
- self.main = MainWindow()
- def show_main(self):
- self.main = MainWindow()
- self.main.setupUi(self.window)
- self.window.show()
- if __name__ == "__main__":
- import sys
- app = QtWidgets.QApplication(sys.argv)
- if platform.system() == "Linux":
- QtWidgets.QApplication.setStyle(QtWidgets.QStyleFactory.create('Fusion'))
- elif platform.system() == "Darwin":
- QtWidgets.QApplication.setStyle(QtWidgets.QStyleFactory.create('Windows'))
- controller = MainController()
- controller.show_main()
- sys.exit(app.exec_())
|