python-记录一个按文档长度分割Excel文件的方法

import tkinter as tk
import pandas as pd
import tkinter.filedialog
import os
import traceback

windows = tk.Tk()


####按长度拆分——自定义函数
##拆分函数
def division_by_length(iterable, length):
    iterable_len = len(iterable)
    start = 0
    while 1:
        if iterable_len > start + length:
            yield iterable[start:start + length]
        else:
            yield iterable[start:]
            return
        start += length


###拆分激活动作,按长度拆分
def split_excel():
    try:
        split_excel_file_path = tkinter.filedialog.askopenfilename(title='请选择要拆分的文件')
        split_sheet = tkinter.simpledialog.askstring(title='拆分sheet', prompt='请输入拆分sheetname:', initialvalue='Sheet1')
        split_num = tkinter.simpledialog.askstring(title='拆分长度', prompt='请输入拆分长度:', initialvalue='100')
        # 获取拆分长度
        length = int(split_num)
        print(split_num, type(split_num))
        # 选中,读取待拆分文件
        split_excel_df = pd.read_excel(split_excel_file_path, dtype=str, sheet_name=split_sheet)
        # print(split_excel_df)
        # 新建结果文件夹
        parent_dir = os.path.dirname(split_excel_file_path)  # 获取拆分文件父文件夹
        for i in parent_dir:
            middleware_file_path_help = os.path.join(parent_dir, "拆分文件")
        if not os.path.exists(middleware_file_path_help):
            os.makedirs(middleware_file_path_help)
        # 执行拆分操作
        split_list = [i for i in division_by_length(split_excel_df, length)]
        n = 1
        for i in split_list:
            i.to_excel(os.path.join(middleware_file_path_help, str(n) + ".xlsx"), index=False)
            n = n + 1
    except Exception as e:
        mes = traceback.format_exc()
        windows.update()


b_split = tk.Button(windows, text="按长度拆分文件", width=15, height=2, command=split_excel)
b_split.pack()
windows.mainloop()
posted @ 2024-05-22 22:25  AZ26  阅读(40)  评论(0)    收藏  举报