Python使用pandas按最大行分割表格文档,转exe工具
- 提升工作效率
- 2024-07-11
- 975热度
- 0评论
环境
pip install pandas -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install openpyxl -i https://pypi.tuna.tsinghua.edu.cn/simple
代码
import tkinter as tk
from tkinter import filedialog, messagebox
import pandas as pd
import os
def select_file():
file_path = filedialog.askopenfilename(filetypes=[("Excel文件", "*.xlsx *.xls")])
file_entry.delete(0, tk.END)
file_entry.insert(0, file_path)
def process_file():
file_path = file_entry.get()
max_rows = int(rows_entry.get())
if not file_path or not max_rows:
messagebox.showwarning("警告", "请选择文件并设定最大行数。")
return
try:
df = pd.read_excel(file_path)
file_name, file_ext = os.path.splitext(file_path)
# Split the DataFrame into chunks
for i, chunk in enumerate(range(0, len(df), max_rows)):
chunk_df = df.iloc[chunk:chunk + max_rows]
output_file = f"{file_name}_part_{i + 1}{file_ext}"
chunk_df.to_excel(output_file, index=False)
messagebox.showinfo("成功", "文件处理成功。")
except Exception as e:
messagebox.showerror("错误", str(e))
# Create the main window
root = tk.Tk()
root.title("Excel文件分割器")
# File selection
file_label = tk.Label(root, text="选择文件:")
file_label.grid(row=0, column=0, padx=10, pady=10)
file_entry = tk.Entry(root, width=50)
file_entry.grid(row=0, column=1, padx=10, pady=10)
file_button = tk.Button(root, text="浏览", command=select_file)
file_button.grid(row=0, column=2, padx=10, pady=10)
# Row limit input
rows_label = tk.Label(root, text="每个文件最大行数:")
rows_label.grid(row=1, column=0, padx=10, pady=10)
rows_entry = tk.Entry(root, width=20)
rows_entry.insert(0, "20") # Set default value to 20
rows_entry.grid(row=1, column=1, padx=10, pady=10)
# Process button
process_button = tk.Button(root, text="开始处理", command=process_file)
process_button.grid(row=2, column=1, pady=20)
# Start the GUI event loop
root.mainloop()