我们在办公中经常需要以Excel中的某一列进行文件拆分(拆分出小文件),今天就与ChatGPT合作了一把,共同完成了这个GUI办公拆分Excel小工具
先看需求图片:
这个需求已经完美解决啦,先看一下视频,是不是你想要的效果:
ChatGPT给的代码始终多多少少有点问题,就会一个劲的说:“非常抱歉”。。。最后我修改了其中的拆分函数,其中主要的界面还是用其代码
如果表头的很长不用担心,选择列是可以滚动的,如下
该工具使用到的库
库名 安装 tkinter pip install tkinter
pandas pip install pandas
openpyxl pip install openpyxl
完整版代码:
import openpyxl
import pandas as pd
import tkinter as tk
from tkinter. filedialog import askopenfilename
from tkinter import messageboxclass SplitterGUI : def __init__ ( self, master) : self. master = mastermaster. title( "Excel拆分小工具" ) self. label1 = tk. Label( master, text= "文件路径:" ) self. label1. grid( row= 0 , column= 0 ) self. filepath_entry = tk. Entry( master, width= 50 ) self. filepath_entry. grid( row= 0 , column= 1 , columnspan= 2 ) self. browse_button = tk. Button( master, text= "浏览" , command= self. browse_files) self. browse_button. grid( row= 0 , column= 3 ) self. label2 = tk. Label( master, text= "表头名称:" ) self. label2. grid( row= 1 , column= 0 ) self. cols_listbox = tk. Listbox( master, selectmode= tk. MULTIPLE, height= 5 , exportselection= False ) self. cols_listbox. grid( row= 2 , column= 0 , rowspan= 4 ) self. scrollbar = tk. Scrollbar( master, orient= tk. VERTICAL) self. scrollbar. grid( row= 2 , column= 1 , rowspan= 4 , sticky= tk. NS) self. cols_listbox. config( yscrollcommand= self. scrollbar. set ) self. scrollbar. config( command= self. cols_listbox. yview) self. split_button = tk. Button( master, text= "开始拆分" , command= self. split_files) self. split_button. grid( row= 6 , column= 3 ) def browse_files ( self) : global filepath, colnamesfilepath = askopenfilename( ) self. filepath_entry. delete( 0 , tk. END) self. filepath_entry. insert( 0 , filepath) df = pd. read_excel( filepath) colnames = list ( df. columns) for col in colnames: self. cols_listbox. insert( tk. END, col) def split_files ( self) : selected_indices = self. cols_listbox. curselection( ) df = pd. read_excel( filepath, usecols= [ colnames[ selected_indices[ 0 ] ] ] , dtype= str , keep_default_na= '' ) cf_list = [ ] for d in df. values. tolist( ) : if d[ 0 ] not in cf_list: cf_list. append( d[ 0 ] ) df_1 = pd. read_excel( filepath, dtype= str , keep_default_na= '' ) a = df_1. groupby( colnames[ selected_indices[ 0 ] ] ) for i in cf_list: wb = openpyxl. Workbook( ) ws = wb. activews. append( colnames) data = a. get_group( str ( i) ) . values. tolist( ) for k in data: print ( k) ws. append( k) wb. save( f"./ { i} .xlsx" ) print ( "-" * 30 ) messagebox. showinfo( "成功" , "拆分完成!请查看生成的文件。" )
root = tk. Tk( )
app = SplitterGUI( root)
root. mainloop( )
友情提示,该功能目前只能选择单一的列进行拆分!
PS .该工具非常适合打包EXE,发给你心爱的同事们使用,
打包教程1:纯净版打包:点我学习
打包教程2:现有环境打包:点我学习
希望对大家有帮助,如有错误,欢迎指正
致力于办公自动化的小小程序员一枚
希望能得到大家的【一个免费关注
】!感谢!