基于PyQt5制作数据处理小工具

 更新时间:2022年03月05日 08:35:36   作者:Python 集中营  
这篇文章主要和大家介绍了如何利用Python中的PyQt5模块制作一个数据处理小工具,可以实现根据每个Excel数据文件里面的Sheet批量将数据文件合并成为一个汇总后的Excel数据文件,需要的可以参考一下

需求分析:

现在有一大堆的Excel数据文件,需要根据每个Excel数据文件里面的Sheet批量将数据文件合并成为一个汇总后的Excel数据文件。或者是将一个汇总后的Excel数据文件按照Sheet拆分成很多个Excel数据文件。根据上面的需求,我们先来进行UI界面的布局设计。

导入UI界面设计相关的PyQt5模块

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

应用操作相关的模块

import sys
import os

excel 数据处理模块

import openpyxl as pxl
import pandas as pd

看一下 UI 界面的功能和布局,感觉还可以...

file

下面是布局相关的代码块实例

    def init_ui(self):
        self.setWindowTitle('Excel数据汇总/拆分器  公众号:[Python 集中营]')
        self.setWindowIcon(QIcon('数据.ico'))

        self.brower = QTextBrowser()
        self.brower.setReadOnly(True)
        self.brower.setFont(QFont('宋体', 8))
        self.brower.setPlaceholderText('批量数据处理进度显示区域...')
        self.brower.ensureCursorVisible()

        self.excels = QLineEdit()
        self.excels.setReadOnly(True)

        self.excels_btn = QPushButton()
        self.excels_btn.setText('加载批文件')
        self.excels_btn.clicked.connect(self.excels_btn_click)

        self.oprate_type = QLabel()
        self.oprate_type.setText('操作类型')

        self.oprate_combox = QComboBox()
        self.oprate_combox.addItems(['数据合并', '数据拆分'])

        self.data_type = QLabel()
        self.data_type.setText('合并/拆分')

        self.data_combox = QComboBox()
        self.data_combox.addItems(['按照Sheet拆分'])

        self.new_file_path = QLineEdit()
        self.new_file_path.setReadOnly(True)

        self.new_file_path_btn = QPushButton()
        self.new_file_path_btn.setText('新文件路径')
        self.new_file_path_btn.clicked.connect(self.new_file_path_btn_click)

        self.thread_ = DataThread(self)
        self.thread_.trigger.connect(self.update_log)
        self.thread_.finished.connect(self.finished)

        self.start_btn = QPushButton()
        self.start_btn.setText('开始数据汇总/拆分')
        self.start_btn.clicked.connect(self.start_btn_click)

        form = QFormLayout()
        form.addRow(self.excels, self.excels_btn)
        form.addRow(self.oprate_type, self.oprate_combox)
        form.addRow(self.data_type, self.data_combox)
        form.addRow(self.new_file_path, self.new_file_path_btn)

        vbox = QVBoxLayout()
        vbox.addLayout(form)
        vbox.addWidget(self.start_btn)

        hbox = QHBoxLayout()
        hbox.addWidget(self.brower)
        hbox.addLayout(vbox)

        self.setLayout(hbox)

槽函数 update_log,将运行过程通过文本浏览器的方式实时展示,方便查看程序的运行。

  def update_log(self, text):
        cursor = self.brower.textCursor()
        cursor.movePosition(QTextCursor.End)
        self.brower.append(text)
        self.brower.setTextCursor(cursor)
        self.brower.ensureCursorVisible()

槽函数 excels_btn_click,绑定到文件加载按钮,处理源文件的加载过程。

 def excels_btn_click(self):
        paths = QFileDialog.getOpenFileNames(self, '选择文件', os.getcwd(), 'Excel File(*.xlsx)')
        files = paths[0]
        path_strs = ''
        for file in files:
            path_strs = path_strs + file + ';'
        self.excels.setText(path_strs)
        self.update_log('已经完成批文件路径加载!')

槽函数 new_file_path_btn_click,选择新文件要保存的路径。

 def new_file_path_btn_click(self):
        directory = QFileDialog.getExistingDirectory(self, '选择文件夹', os.getcwd())
        self.new_file_path.setText(directory)

槽函数 start_btn_click,绑定到开始按钮上,使用开始按钮启动子线程工作。

    def start_btn_click(self):
        self.start_btn.setEnabled(False)
        self.thread_.start()

函数 finished,这个函数是用来接收子线程传过来的运行完成的信号,通过判断使子线程执行完成时让开始按钮处于可以点击的状态。

 def finished(self, finished):
        if finished is True:
            self.start_btn.setEnabled(True)

下面是最重要的逻辑处理部分,将所有的逻辑处理相关的部分全部放到子线程中去执行。

class DataThread(QThread):
    trigger = pyqtSignal(str)
    finished = pyqtSignal(bool)

    def __init__(self, parent=None):
        super(DataThread, self).__init__(parent)
        self.parent = parent
        self.working = True

    def __del__(self):
        self.working = False
        self.wait()

    def run(self):
        self.trigger.emit('启动批量处理子线程...')
        oprate_type = self.parent.oprate_combox.currentText().strip()
        data_type = self.parent.data_combox.currentText().strip()
        files = self.parent.excels.text().strip()
        new_file_path = self.parent.new_file_path.text()
        if data_type == '按照Sheet拆分' and oprate_type == '数据合并':
            self.merge_data(files=files, new_file_path=new_file_path)
        elif data_type == '按照Sheet拆分' and oprate_type == '数据拆分':
            self.split_data(files=files, new_file_path=new_file_path)
        else:
            pass
        self.trigger.emit('数据处理完成...')
        self.finished.emit(True)

    def merge_data(self, files, new_file_path):
        num = 1
        new_file = new_file_path + '/数据汇总.xlsx'
        writer = pd.ExcelWriter(new_file)
        for file in files.split(';'):
            if file.strip() != '':
                web_sheet = pxl.load_workbook(file)
                sheets = web_sheet.sheetnames
                for sheet in sheets:
                    sheet_name = sheet.title()
                    self.trigger.emit('准备处理工作表名称:' + str(sheet.title()))
                    data_frame = pd.read_excel(file, sheet_name=sheet_name)
                    sheet_name = sheet_name + 'TO数据合并' + str(num)
                    data_frame.to_excel(writer, sheet_name, index=False)
                    num = num + 1
            else:
                self.trigger.emit('当前路径为空,继续...')
        writer.save()
        writer.close()

    def split_data(self, files, new_file_path):
        num = 1
        for file in files.split(';'):
            if file.strip() != '':
                web_sheet = pxl.load_workbook(file)
                sheets = web_sheet.sheetnames
                for sheet in sheets:
                    sheet_name = sheet.title()
                    self.trigger.emit('准备处理工作表名称:' + str(sheet.title()))
                    data_frame = pd.read_excel(file, sheet_name=sheet_name)
                    writer = pd.ExcelWriter(new_file_path + '/数据拆分' + str(num) + '.xlsx')
                    data_frame.to_excel(writer, '数据拆分', index=False)
                    writer.save()
                    writer.close()
                    num = num + 1
            else:
                self.trigger.emit('当前路径为空,继续...')

上面就是主要的代码块实现过程,有需要的可以参考一下。欢迎大佬在评论区进行留言。

搞了一个程序运行效果图,看一下执行效果。

file

完整代码

# -*- coding:utf-8 -*-
# @author Python 集中营
# @date 2022/1/12
# @file test8.py

# done

# 数据处理小工具:Excel 批量数据文件拆分/整合器

# 需求分析:
# 现在有一大堆的Excel数据文件,需要根据每个Excel数据文件里面的Sheet批量将数据文件
# 合并成为一个汇总后的Excel数据文件。
# 或者是将一个汇总后的Excel数据文件按照Sheet拆分成很多个Excel数据文件。
# 根据上面的需求,我们先来进行UI界面的布局设计。

# 导入UI界面设计相关的PyQt5模块

from PyQt5.QtWidgets import *

from PyQt5.QtCore import *

from PyQt5.QtGui import *

# 应用操作相关的模块

import sys
import os

# excel 数据处理模块
import openpyxl as pxl
import pandas as pd


class ExcelDataMerge(QWidget):

    def __init__(self):
        super(ExcelDataMerge, self).__init__()
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('Excel数据汇总/拆分器  公众号:[Python 集中营]')
        self.setWindowIcon(QIcon('数据.ico'))

        self.brower = QTextBrowser()
        self.brower.setReadOnly(True)
        self.brower.setFont(QFont('宋体', 8))
        self.brower.setPlaceholderText('批量数据处理进度显示区域...')
        self.brower.ensureCursorVisible()

        self.excels = QLineEdit()
        self.excels.setReadOnly(True)

        self.excels_btn = QPushButton()
        self.excels_btn.setText('加载批文件')
        self.excels_btn.clicked.connect(self.excels_btn_click)

        self.oprate_type = QLabel()
        self.oprate_type.setText('操作类型')

        self.oprate_combox = QComboBox()
        self.oprate_combox.addItems(['数据合并', '数据拆分'])

        self.data_type = QLabel()
        self.data_type.setText('合并/拆分')

        self.data_combox = QComboBox()
        self.data_combox.addItems(['按照Sheet拆分'])

        self.new_file_path = QLineEdit()
        self.new_file_path.setReadOnly(True)

        self.new_file_path_btn = QPushButton()
        self.new_file_path_btn.setText('新文件路径')
        self.new_file_path_btn.clicked.connect(self.new_file_path_btn_click)

        self.thread_ = DataThread(self)
        self.thread_.trigger.connect(self.update_log)
        self.thread_.finished.connect(self.finished)

        self.start_btn = QPushButton()
        self.start_btn.setText('开始数据汇总/拆分')
        self.start_btn.clicked.connect(self.start_btn_click)

        form = QFormLayout()
        form.addRow(self.excels, self.excels_btn)
        form.addRow(self.oprate_type, self.oprate_combox)
        form.addRow(self.data_type, self.data_combox)
        form.addRow(self.new_file_path, self.new_file_path_btn)

        vbox = QVBoxLayout()
        vbox.addLayout(form)
        vbox.addWidget(self.start_btn)

        hbox = QHBoxLayout()
        hbox.addWidget(self.brower)
        hbox.addLayout(vbox)

        self.setLayout(hbox)

    def update_log(self, text):
        cursor = self.brower.textCursor()
        cursor.movePosition(QTextCursor.End)
        self.brower.append(text)
        self.brower.setTextCursor(cursor)
        self.brower.ensureCursorVisible()

    def excels_btn_click(self):
        paths = QFileDialog.getOpenFileNames(self, '选择文件', os.getcwd(), 'Excel File(*.xlsx)')
        files = paths[0]
        path_strs = ''
        for file in files:
            path_strs = path_strs + file + ';'
        self.excels.setText(path_strs)
        self.update_log('已经完成批文件路径加载!')

    def new_file_path_btn_click(self):
        directory = QFileDialog.getExistingDirectory(self, '选择文件夹', os.getcwd())
        self.new_file_path.setText(directory)

    def start_btn_click(self):
        self.start_btn.setEnabled(False)
        self.thread_.start()

    def finished(self, finished):
        if finished is True:
            self.start_btn.setEnabled(True)


class DataThread(QThread):
    trigger = pyqtSignal(str)
    finished = pyqtSignal(bool)

    def __init__(self, parent=None):
        super(DataThread, self).__init__(parent)
        self.parent = parent
        self.working = True

    def __del__(self):
        self.working = False
        self.wait()

    def run(self):
        self.trigger.emit('启动批量处理子线程...')
        oprate_type = self.parent.oprate_combox.currentText().strip()
        data_type = self.parent.data_combox.currentText().strip()
        files = self.parent.excels.text().strip()
        new_file_path = self.parent.new_file_path.text()
        if data_type == '按照Sheet拆分' and oprate_type == '数据合并':
            self.merge_data(files=files, new_file_path=new_file_path)
        elif data_type == '按照Sheet拆分' and oprate_type == '数据拆分':
            self.split_data(files=files, new_file_path=new_file_path)
        else:
            pass
        self.trigger.emit('数据处理完成...')
        self.finished.emit(True)

    def merge_data(self, files, new_file_path):
        num = 1
        new_file = new_file_path + '/数据汇总.xlsx'
        writer = pd.ExcelWriter(new_file)
        for file in files.split(';'):
            if file.strip() != '':
                web_sheet = pxl.load_workbook(file)
                sheets = web_sheet.sheetnames
                for sheet in sheets:
                    sheet_name = sheet.title()
                    self.trigger.emit('准备处理工作表名称:' + str(sheet.title()))
                    data_frame = pd.read_excel(file, sheet_name=sheet_name)
                    sheet_name = sheet_name + 'TO数据合并' + str(num)
                    data_frame.to_excel(writer, sheet_name, index=False)
                    num = num + 1
            else:
                self.trigger.emit('当前路径为空,继续...')
        writer.save()
        writer.close()

    def split_data(self, files, new_file_path):
        num = 1
        for file in files.split(';'):
            if file.strip() != '':
                web_sheet = pxl.load_workbook(file)
                sheets = web_sheet.sheetnames
                for sheet in sheets:
                    sheet_name = sheet.title()
                    self.trigger.emit('准备处理工作表名称:' + str(sheet.title()))
                    data_frame = pd.read_excel(file, sheet_name=sheet_name)
                    writer = pd.ExcelWriter(new_file_path + '/数据拆分' + str(num) + '.xlsx')
                    data_frame.to_excel(writer, '数据拆分', index=False)
                    writer.save()
                    writer.close()
                    num = num + 1
            else:
                self.trigger.emit('当前路径为空,继续...')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = ExcelDataMerge()
    main.show()
    sys.exit(app.exec_())

以上就是基于PyQt5制作数据处理小工具的详细内容,更多关于PyQt5数据处理工具的资料请关注脚本之家其它相关文章!

相关文章

  • Python中Parser的超详细用法实例

    Python中Parser的超详细用法实例

    Parser模块为Python的内部解析器和字节码编译器提供了一个接口,该接口的主要目的是允许Python代码编辑Python表达式的分析树并从中创建可执行代码,这篇文章主要给大家介绍了关于Python中Parser超详细用法的相关资料,需要的朋友可以参考下
    2022-07-07
  • python通过socket查询whois的方法

    python通过socket查询whois的方法

    这篇文章主要介绍了python通过socket查询whois的方法,涉及Python基于socket模块进行查询的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-07-07
  • Python爬虫必备之Xpath简介及实例讲解

    Python爬虫必备之Xpath简介及实例讲解

    xpath是一种在XML文档中定位元素的语言,常用于xml、html文件解析,比css选择器使用方便,下面这篇文章主要给大家介绍了关于Python爬虫必备之Xpath简介及实例的相关资料,需要的朋友可以参考下
    2022-04-04
  • Python pip安装模块提示错误解决方案

    Python pip安装模块提示错误解决方案

    这篇文章主要介绍了Python pip安装模块提示错误解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-05-05
  • Django封装交互接口代码

    Django封装交互接口代码

    这篇文章主要介绍了Django封装交互接口代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-07-07
  • Python Tkinter实现简易计算器功能

    Python Tkinter实现简易计算器功能

    这篇文章主要为大家详细介绍了Python Tkinter实现简易计算器功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-01-01
  • python kmeans聚类简单介绍和实现代码

    python kmeans聚类简单介绍和实现代码

    这篇文章主要为大家详细介绍了python kmeans聚类简单介绍和实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-02-02
  • Python链式调用数据处理实际应用实例探究

    Python链式调用数据处理实际应用实例探究

    本文将深入介绍Python链式调用的概念、原理以及实际应用,通过丰富的示例代码,帮助读者更全面地理解和应用这一编程技巧
    2024-01-01
  • Python虚拟机之super超级魔法的使用和工作原理详解

    Python虚拟机之super超级魔法的使用和工作原理详解

    在本篇文章中,我们将深入探讨Python中的super类的使用和内部工作原理,super类作为Python虚拟机中强大的功能之一,super 可以说是 Python 对象系统基石,他可以帮助我们更灵活地使用继承和方法调用,需要的朋友可以参考下
    2023-10-10
  • Python使用reportlab将目录下所有的文本文件打印成pdf的方法

    Python使用reportlab将目录下所有的文本文件打印成pdf的方法

    这篇文章主要介绍了Python使用reportlab将目录下所有的文本文件打印成pdf的方法,涉及reportlab模块操作pdf文件的相关技巧,需要的朋友可以参考下
    2015-05-05

最新评论