Python对文件的处理,GuI窗口化
虽然没有干it 的行业,但是干别的行业编程学好了,工作效率也是翻倍做这个原因是,目前任职的岗位需要每天对客户的订单汇总做统计交给仓库
重复劳动肯定是不可能的,因为每天订单的文件类型是固定的无非是pdf 或者 excel,大不了里面多套几层if 语句
不懂的问ai,优化也是ai 真的很爽。做完也能分享给同事{:301_978:}
from typing import List, Any
from openpyxl import load_workbook
import my_request
import PyPDF2
import os
import tkinter as tk
from tkinter import filedialog, messagebox
import threading
import sys
# 自定义控制台输出到GUI
class RedirectText:
def __init__(self, text_widget):
self.text_widget = text_widget
def write(self, string):
self.text_widget.insert(tk.END, string)
self.text_widget.see(tk.END)# 自动滚动到最后一行
def flush(self):
pass
# 获取excel文件的数据
def read_excel(file_path: str) -> List:
reads_excel = load_workbook(file_path)
try:
sheet = reads_excel["選型表"]
wb_pc_blank = sheet["A1"].value
wb_number_blank = sheet["G2"].value
if wb_pc_blank is not None and isinstance(wb_pc_blank, str):
wb_pc_del_blank = wb_pc_blank.replace(" ", "")
wb_pc = wb_pc_del_blank.replace("選型表", "")
else:
wb_pc = ""
if wb_number_blank is not None and isinstance(wb_number_blank, str):
wb_number = wb_number_blank.replace("商品數量: ", "")
else:
wb_number = ""
print("截取字段", wb_pc, wb_number)
return
except KeyError as e:
print("俄文走这里", e)
sheet = reads_excel["Лист подбора"]
wb_pc_blank = sheet["A1"].value
wb_number_blank = sheet["G2"].value
if wb_pc_blank is not None and isinstance(wb_pc_blank, str):
wb_pc_del_blank = wb_pc_blank.replace(" ", "")
wb_pc = wb_pc_del_blank.replace("Листподбора", "")
else:
wb_pc = ""
if wb_number_blank is not None and isinstance(wb_number_blank, str):
wb_number = wb_number_blank.replace("Количество товаров: ", "")
else:
wb_number = ""
print("截取字段", wb_pc, wb_number)
return
def read_pdf(file_path: str) -> List:
with open(file_path, 'rb') as file:
reader = PyPDF2.PdfReader(file)
list_pdf_str = []
page = reader.pages
text = page.extract_text()
if text:
lines = text.split('\n')
first_two_lines = lines[:2]
for line in first_two_lines:
list_pdf_str.append(line)
search_string = "Лист"
first_str_list = list_pdf_str.split()
first_str = first_str_list
if first_str == search_string:
wb_str = list_pdf_str.replace("Лист подбора ", "")
wb_number_sp = list_pdf_str.split()
wb_number = int(wb_number_sp[-1])
print("截取字段", wb_str, wb_number)
else:
wb_str = list_pdf_str.replace("選型表 ", "")
wb_number_sp = list_pdf_str.split()
wb_number = str(wb_number_sp[-1])
print("截取字段", wb_str, wb_number)
return
def list_files_in_directory(directory: str) -> List:
files_name = []
for root, dirs, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
files_name.append(file_path)
print("成功获取文件" + file_path)
return files_name
def judge(file_path: str) -> bool:
_, file_extension = os.path.splitext(file_path)
file_extension = file_extension.lower()
try:
if file_extension in ['.xls', '.xlsx']:
return True
elif file_extension == '.pdf':
return False
except Exception as e:
print(file_path + "该文件类型错误")
def clear_data_below_header(sheet, start_row, start_col):
max_row = sheet.max_row
max_col = sheet.max_column
for row in range(start_row, max_row + 1):
for col in range(start_col, max_col + 1):
cell = sheet.cell(row=row, column=col)
cell.value = None
def write_excel(file_path_list: List):
start_col = 1
write_data_list = []
order_number = 0
sum_goods = 0
for file_path_name in file_path_list:
is_type = judge(file_path_name)
if is_type:
order_number += 1
data_pc = read_excel(file_path_name)
cs_id = my_request.wb_pc_search(data_pc)
data_pc.insert(0, cs_id)
data_pc.insert(0, order_number)
print(cs_id)
write_data_list.append(data_pc)
else:
order_number += 1
data_pc = read_pdf(file_path_name)
cs_id = my_request.wb_pc_search(data_pc)
data_pc.insert(0, cs_id)
data_pc.insert(0, order_number)
print(cs_id)
write_data_list.append(data_pc)
file_path = '../File/尾程记录表.xlsx'
workbook = load_workbook(file_path)
sheet = workbook['Sheet1']
clear_data_below_header(sheet, start_row=2, start_col=1)
for row_idx, row_data in enumerate(write_data_list, start=2):
for col_offset, value in enumerate(row_data):
col_idx = start_col + col_offset
if isinstance(value, str):
if value.isdigit():
value = int(value)
else:
try:
value = float(value)
except ValueError:
pass
sheet.cell(row=row_idx, column=col_idx, value=value)
print("写入文件 " + str(value))
for number in write_data_list:
sum_goods = sum_goods + int(number)
list_size = len(write_data_list)
print(f"\n已成功写入!\n\n合计文件 {list_size}个,货物数量合计{sum_goods}个。\n\n客户代码为空表示系统内没有这个批次或抓取失败!")
workbook.save(file_path)
def select_directory(entry_widget):
directory = filedialog.askdirectory()
if directory:
entry_widget.delete(0, tk.END)
entry_widget.insert(0, directory)
# 处理文件函数
def start_processing(directory_path):
if not directory_path:
messagebox.showwarning("警告", "请先选择文件夹路径!")
return
thread = threading.Thread(target=process_files, args=(directory_path,))
thread.start()
# 输出控制台日志
def process_files(directory_path):
list_file_path = list_files_in_directory(directory_path)
write_excel(list_file_path)
messagebox.showinfo("完成", "已成功写入文件!")
# 软件详情
def show_info():
info_text = ("Author: 鱼儿游\n"
"编译时间版本: 2024-08-09/ V-0.02\n"
"说明:对指定路径下所有拣货单进行读取,"
"需要在连接网络的状态下使用。否则无法读取客户代码。")
messagebox.showinfo("软件信息", info_text)
def create_gui():
root = tk.Tk()
root.title("尾程订单批量文件处理工具")
root.geometry("600x500")
# 设置窗口图标
root.iconbitmap('../fish.ico')
# 上部框架
top_frame = tk.Frame(root)
top_frame.pack(pady=20, padx=20, fill=tk.X)
# 路径选择部分
label = tk.Label(top_frame, text="请选择文件夹路径:")
label.pack(side=tk.LEFT, padx=(0, 10))
path_entry = tk.Entry(top_frame, width=40)
path_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
browse_button = tk.Button(top_frame, text="浏览", command=lambda: select_directory(path_entry))
browse_button.pack(side=tk.LEFT, padx=(10, 0))
process_button = tk.Button(root, text="开始处理", command=lambda: start_processing(path_entry.get()))
process_button.pack(pady=10)
# 信息按钮
info_button = tk.Button(root, text="软件信息", command=show_info)
info_button.pack(pady=10)
# 控制台输出区域
console_frame = tk.Frame(root)
console_frame.pack(pady=10, padx=20, fill=tk.BOTH, expand=True)
text_console = tk.Text(console_frame, wrap='word', height=20)
text_console.pack(fill=tk.BOTH, expand=True)
# 禁止用户在 Text 控件中输入文字
text_console.bind("<Key>", lambda e: "break")
# 将 sys.stdout 重定向到 text_console
redirect_text = RedirectText(text_console)
sys.stdout = redirect_text
root.mainloop()
if __name__ == '__main__':
create_gui()
这是 核心的东西,另外导入的import my_request包是我自己的网络请求代码,里面涉及公司系统的隐私就不放了,主要是获取客户的代码然后填入表格
eheweh 发表于 2024-8-9 22:08
学习学习,ai能生成窗口吗,生成GUI不知道怎么提问。。
直接说实现窗口化就行 能力越强工作越多! 学习学习,ai能生成窗口吗,生成GUI不知道怎么提问。。 每天显得忙碌,才是你升职加薪不被炒的唯一途径 虽然用不着,鼓励一下! thornjay 发表于 2024-8-10 09:55
每天显得忙碌,才是你升职加薪不被炒的唯一途径
样子装不来{:1_907:},重复劳动浪费时间。 一开头就看到了好几个不认识的库,俺还得再学学…… 我丢,又有不知道的,还真是活到老学到老 正好需要一个类似的GUI,直接抄了
页:
[1]
2