Tips | Write a table splitting and merging gadget yourself with 80 lines of code

Release: 2023-08-10 16:02:48
forward
1227 people have browsed it


Recently some new friends have seen the previous article "Comparing Python with VBA to implement excel table merging and splitting" Split", I would like to ask if there is any free gadget that can split and mergetables. In fact,wpshas these two functions, and the effect is very good. However, considering that everyone may not be used towps, here we simply write a small tool to satisfy everyone.

Let’s take a look at the gadget operation process first!

The effects of merging and splitting are as follows:

Tips | Write a table splitting and merging gadget yourself with 80 lines of code
Merge - Split

Next, let’s try Try writing this tool yourself!

1. Preliminary preparation

Since we usepythonfor tool writing, and ultimately need Packaged into anexefile for our use. In order to reduce the package size, we need to first create avirtual environmentfor backup.

In addition, the third-party librarypandasis used for table splitting and merging operations. At the same time, we usepysimpleguifor the gui, which is packaged into exe. The one ispyinstaller. After creating the virtual environment, let's install the third-party libraries we need to use one by one.

# 创建虚拟环境 conda create -n env_1 python=3.8.8 # 激活虚拟环境 conda activate env_1 # 安装三个库 (pandas一些操作需要依赖openpyxl和xlrd,建议加上) pip install pandas pip install openpyxl pip install xlrd pip install pysimplegui pip install pyinstaller
Copy after login

Regarding these three libraries, you can check the official documentation to learn more:

pandas: https://pandas.pydata. org/

##pysimplegui:https://pysimplegui.readthedocs.io/en/latest/

pyinstaller: http://www.pyinstaller.org/

The early preparation tools are ready, and we begin to enter the tool writing stage.

2. 表格拆分

Python实现表格拆分的逻辑比较简单,就是利用pandas分组然后将每组的数据单独导出存表即可

原表数据长这样:

Tips | Write a table splitting and merging gadget yourself with 80 lines of code
汇总表
# 拆分表格 def splitTable(df,_key): print('----------正在进行表格拆分----------') df = df.astype('str') # 按照字段_key进行分组 grouped = df.groupby(by = _key) # 输出分组数据导出成单表 for num , (i, data) in enumerate(grouped): data.to_excel(f'.\\{i}.xlsx',index = False,sheet_name = i) print(f'已经拆成{num+1}张表格...')
Copy after login

导出结果如下:

Tips | Write a table splitting and merging gadget yourself with 80 lines of code
拆分

3. 表格合并

Python实现表格合并的本质是遍历全部表格数据,然后采用concat方法进行数据合并Pandas学习笔记02-数据合并

因此,在这里我们主要用到两个库:ospandas,其中os用于获取文件夹下全部满足要求的文件信息,pandas用于读取表格数据并进行concat

# 合并表格 def concatTable(folder): print('----------正在进行表格合并----------') # 新建一个空列表,用于存储表格数据 fileList = [] # 把文件夹下表格数据放在一个列表里 for fileName in os.walk(folder): for table in fileName[2]: path = fileName[0] + '\\' + table if os.path.splitext(path)[1] in ('.xlsx','.xls'): li = pd.read_excel(path) fileList.append(li) print(f'已读取{len(fileList)}个表格...') else: continue # 用concat方法合并表单数据 result = pd.concat(fileList) # 导出数据 result.to_excel(r'.\合并后文件.xlsx',index=False,sheet_name='汇总')
Copy after login

4. GUI设计

因为要支持表格拆分和合并,我们已经在2和3部分将这两个功能封装为函数了。

Regarding the functional part of the GUI, the following functions need to be supported.

For the table splitting part, function points:

  • Select file: Text InputText FileBrowse
  • Split field selection after reading the file: Text Combo
  • Split: Button
##For table merge part ,function points:

  • 选取文件夹: Text InputText FolderBrowse
  • 合并: Button

此外,我们还需要有用于展示 程序操作记录的输出框、工具操作说明文本以及关闭程序按钮。

基于以上需求,我们可以构建GUI布局如下:

# 布局设置 layout = [[sg.Text('选择待拆分的文件:',font=("微软雅黑", 12)),sg.InputText(key='file',size=(60,1),font=("微软雅黑", 10),enable_events=True) ,sg.FileBrowse('打开',file_types=(("Text Files", "*.xls*"),),font=("微软雅黑", 12))], [sg.Text('选择待拆分的字段:',font=("微软雅黑", 12)),sg.Combo('',tooltip='选择用于拆分的字段',font=("微软雅黑", 10), default_value='',auto_size_text=True,size=(15, 5),key='-keys-'),sg.Button('开始拆分',font=("微软雅黑", 12))], [sg.Text('选择待合并文件夹:',font=("微软雅黑", 12)),sg.InputText(key='Folder',size=(60,1),font=("微软雅黑", 10),enable_events=True) ,sg.FolderBrowse('打开文件夹',font=("微软雅黑", 12)),sg.Button('开始合并',font=("微软雅黑", 12))], [sg.Text('程序操作记录:',justification='center')], [sg.Output(size=(100, 10),font=("微软雅黑", 10))], [sg.Text('操作说明:',font=("微软雅黑", 12))], [sg.Text('表格拆分指引:选择文件—>选择用于拆分的字段—>开始拆分\n表格合并指引:选择需要合并的表格所在文件夹—>开始合并',font=("微软雅黑", 10)),sg.Text('',font=("微软雅黑", 12),size=(35, 1)),sg.Button('关闭程序',font=("微软雅黑", 12),button_color ='red')] ]
Copy after login

由于我们在进行表格拆分时需要先选定文件及拆分字段,而拆分字段是在选定文件后读取到的文件数据的表头,所以需要在sg.InputText()中将参数enable_events设置为True,这样选定文件操作就是一个事件,可以触发某些操作。

接下来,我们编写循环事件功能如下:

# 事件循环 while True: event, values = window.read() if event in (None, '关闭程序'): break if event == 'file': fileName = values['file'] if os.path.exists(fileName): df = pd.read_excel(fileName) keys = df.columns.to_list() window["-keys-"].Update(values = keys,font=("微软雅黑", 10),size=(15, 8)) else: print('文件不存在\n请先选择正确文件') if event == '开始拆分': if values['-keys-']: _key = values['-keys-'] splitTable(df,_key) print('----------拆分工作已经完成----------\n') else: print('字段未选择-请先选择字段\n或文件未选取-请先选择文件') if event == '开始合并': if values['Folder']: folder = values['Folder'] concatTable(folder) print('----------合并工作已经完成----------\n') else: print('待合并文件所在文件夹未选择') window.close()
Copy after login

根据需求,我们将事件类型分为三种:

  • 当我们 选定待拆分文件后,先读取文件内容,然后获取文件数据的表头,从而刷新( window["-keys-"].Update)拆分字段的下拉框为表头内容;
  • 当我们点击 开始拆分按钮时,需要判断拆分字段是否选取(默认为空),若有选定字段则进行拆分操作,否则会进行错误操作提示;
  • 当我们点击 开始合并按钮时,需要判断是否选定了文件夹,若是则调用合并数据函数进行合并操作,否则会进行错误操作提示。

5. 打包代码

这里采用的是pyinstaller进行程序代码打包,操作指令如下:

pyinstaller -F -w 表格拆分合并工具.py
Copy after login

部分参数含义:

-F 表示生成单个可执行文件

-w 表示去掉控制台窗口,这在GUI界面时非常有用

-p 表示你自己自定义需要加载的类路径,一般情况下用不到

-i 表示可执行文件的图标

The above is the detailed content of Tips | Write a table splitting and merging gadget yourself with 80 lines of code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Python当打之年
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!