import tkinter as tk
import os
import tkinter.filedialog
import tkinter.simpledialog
import pandas as pd
import tkinter.messagebox
import tkinter.ttk
import traceback
global column, sheet_ori
global combox_2
# 按内容分类
def split_by_group():
# 获取需要拆分文件的路径,表明,列名
split_excel = tkinter.filedialog.askopenfilename(title='选择需要拆分的excel文件')
sub_win = tk.Tk()
sub_win.geometry("350x150")
file = pd.ExcelFile(split_excel)
sheets = file.sheet_names
combox_1 = tk.ttk.Combobox(sub_win, width=20)
combox_1['values'] = sheets
combox_1["state"] = "readonly"
label1 = tk.Label(sub_win,text='选择工作表')
label1.grid(row=0,column=0)
combox_1.grid(row=0, column=1)
def split_process(*args):
# 新建拆分结果路径
global combox_2, sheet_ori
notice = tkinter.messagebox.showinfo(title='信息提示!', message='选取拆分文件生成路径')
split_col = combox_2.get()
parent_dir = tk.filedialog.askdirectory()
print(parent_dir)
middleware_file_path = os.path.join(parent_dir, "拆分文件")
if not os.path.exists(middleware_file_path):
os.makedirs(middleware_file_path)
# 读取拆分文件,并进行拆分动作
df = pd.read_excel(split_excel, dtype=str, sheet_name=sheet_ori)
a = 0
for i, value in df.groupby(split_col):
a = a + 1
name_1 = value[split_col].tolist()[0]
print(name_1)
value.to_excel(os.path.join(middleware_file_path, str(name_1) + ".xlsx"), index=None)
# 用获取的表名获取全部列名
def appear(*args):
global combox_2, sheet_ori
sheet_ori = combox_1.get() # 选择后激活获取
print(sheet_ori)
df_total = pd.read_excel(file, sheet_name=sheet_ori)
columns = df_total.columns.values.tolist()
print(columns)
label2 = tk.Label(sub_win,text='选择拆分依据列')
label2.grid(row=1, column=0)
combox_2 = tk.ttk.Combobox(sub_win, width=20)
combox_2['values'] = columns
combox_2['state'] = 'readonly'
combox_2.grid(row=1, column=1)
label1 = tk.Label(sub_win, text="选择完拆分列后" + "\n" + "选择结果生成文件夹" + "\n" + "选择完成后开始运行" + "\n" + '不选择则生成在软件本体文件夹')
label1.grid(row=2, column=0)
combox_2.bind('<<ComboboxSelected>>', split_process)
combox_1.bind('<<ComboboxSelected>>', appear)
sub_win.update()
sub_win.mainloop()
res = traceback.format_exc()
return res
split_by_group()
标签:sheet,sub,combox,win,Excel,按列,split,拆分
From: https://www.cnblogs.com/AZ26/p/18207269