feat(ui): 界面全面升级为无边框扁平化设计,新增自定义 ProgressButton 及中途暂停确认功能
This commit is contained in:
+33
-7
@@ -36,7 +36,7 @@ def detect_and_create_apps():
|
||||
raise RuntimeError("未检测到可用的办公套件!请确保电脑已安装 Microsoft Office 或 WPS。")
|
||||
|
||||
|
||||
def export_single_doc_tables(word_app, excel_app, doc_path, excel_path, log_func=None):
|
||||
def export_single_doc_tables(word_app, excel_app, doc_path, excel_path, log_func=None, debug=False):
|
||||
"""提取单个 Word 文件中的所有表格到 Excel"""
|
||||
abs_doc = os.path.abspath(doc_path)
|
||||
abs_excel = os.path.abspath(excel_path)
|
||||
@@ -44,19 +44,26 @@ def export_single_doc_tables(word_app, excel_app, doc_path, excel_path, log_func
|
||||
doc = None
|
||||
wb = None
|
||||
try:
|
||||
doc = word_app.Documents.Open(abs_doc, ReadOnly=True)
|
||||
if debug and log_func:
|
||||
log_func(f" [Debug] 正在调用 COM 接口打开文档: {abs_doc}")
|
||||
doc = word_app.Documents.Open(FileName=abs_doc, ReadOnly=True, Visible=debug)
|
||||
table_count = doc.Tables.Count
|
||||
|
||||
if table_count == 0:
|
||||
if log_func:
|
||||
log_func(f" [跳过] 未检测到表格: {os.path.basename(doc_path)}")
|
||||
return False
|
||||
return 0
|
||||
|
||||
wb = excel_app.Workbooks.Add()
|
||||
|
||||
for i in range(1, table_count + 1):
|
||||
if debug and log_func:
|
||||
log_func(f" [Debug] 正在提取 第 {i}/{table_count} 个表格...")
|
||||
table = doc.Tables.Item(i)
|
||||
table.Range.Copy()
|
||||
|
||||
import time
|
||||
time.sleep(0.2) # 给系统剪贴板同步数据留点时间
|
||||
|
||||
if i > wb.Sheets.Count:
|
||||
ws = wb.Sheets.Add(After=wb.Sheets(wb.Sheets.Count))
|
||||
@@ -64,20 +71,39 @@ def export_single_doc_tables(word_app, excel_app, doc_path, excel_path, log_func
|
||||
ws = wb.Sheets.Item(i)
|
||||
|
||||
ws.Name = f"Table_{i}"
|
||||
ws.Paste()
|
||||
|
||||
# Excel的Paste可能会因为剪贴板被占用而报错 0x800A03EC,加入重试机制
|
||||
for retry in range(3):
|
||||
try:
|
||||
ws.Paste()
|
||||
break
|
||||
except Exception as pe:
|
||||
if debug and log_func:
|
||||
log_func(f" [Debug] 粘贴报错 {pe},等待0.5秒后重试...")
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
ws.Paste() # 最后一次尝试,若失败则抛出异常
|
||||
|
||||
ws.Columns.AutoFit()
|
||||
|
||||
while wb.Sheets.Count > table_count:
|
||||
wb.Sheets(wb.Sheets.Count).Delete()
|
||||
|
||||
wb.SaveAs(abs_excel)
|
||||
# 51 = xlOpenXMLWorkbook (.xlsx)
|
||||
if os.path.exists(abs_excel):
|
||||
try:
|
||||
os.remove(abs_excel)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
wb.SaveAs(Filename=abs_excel, FileFormat=51)
|
||||
if log_func:
|
||||
log_func(f" [成功] 提取完成 ({table_count}个表格) -> {os.path.basename(excel_path)}")
|
||||
return True
|
||||
return table_count
|
||||
finally:
|
||||
if wb:
|
||||
try:
|
||||
wb.Close(SaveChanges=True)
|
||||
wb.Close(SaveChanges=False)
|
||||
except Exception:
|
||||
pass
|
||||
if doc:
|
||||
|
||||
+362
-33
@@ -6,14 +6,75 @@ import tkinter as tk
|
||||
from tkinter import filedialog, messagebox, ttk
|
||||
import pythoncom
|
||||
import windnd
|
||||
import datetime
|
||||
|
||||
from config import CONFIG_FILE
|
||||
from config import CONFIG_FILE, APP_DIR
|
||||
from extractor import detect_and_create_apps, export_single_doc_tables
|
||||
|
||||
class ProgressButton(tk.Canvas):
|
||||
def __init__(self, master, text="", command=None, **kwargs):
|
||||
bg = kwargs.pop('bg', '#e1e1e1')
|
||||
height = kwargs.pop('height', 32)
|
||||
cursor = kwargs.pop('cursor', 'hand2')
|
||||
super().__init__(master, bg=bg, highlightthickness=1, highlightbackground="#cccccc", highlightcolor="#cccccc", height=height, cursor=cursor, **kwargs)
|
||||
self.command = command
|
||||
self.progress = 0.0
|
||||
|
||||
self.bg_color = bg
|
||||
self.fill_color = "#4caf50"
|
||||
self.hover_color = "#d5d5d5"
|
||||
|
||||
self.rect_id = self.create_rectangle(0, 0, 0, 0, fill=self.fill_color, width=0)
|
||||
self.text_id = self.create_text(0, 0, text=text, fill="black", font=("Microsoft YaHei", 10))
|
||||
|
||||
self.bind("<Button-1>", self._on_click)
|
||||
self.bind("<Enter>", self._on_enter)
|
||||
self.bind("<Leave>", self._on_leave)
|
||||
self.bind("<Configure>", self._on_resize)
|
||||
|
||||
def _on_click(self, event):
|
||||
if self.command:
|
||||
self.command()
|
||||
|
||||
def _on_enter(self, event):
|
||||
self.config(bg=self.hover_color)
|
||||
|
||||
def _on_leave(self, event):
|
||||
self.config(bg=self.bg_color)
|
||||
|
||||
def _on_resize(self, event):
|
||||
self._update_layout()
|
||||
|
||||
def _update_layout(self):
|
||||
w = self.winfo_width()
|
||||
h = self.winfo_height()
|
||||
self.coords(self.rect_id, 0, 0, w * self.progress, h)
|
||||
self.coords(self.text_id, w / 2, h / 2)
|
||||
|
||||
def config_btn(self, text=None, command=None, state=None):
|
||||
if text is not None:
|
||||
self.itemconfig(self.text_id, text=text)
|
||||
if command is not None:
|
||||
self.command = command
|
||||
if state == tk.DISABLED:
|
||||
self.config(cursor="arrow", bg=self.bg_color)
|
||||
self.unbind("<Button-1>")
|
||||
self.unbind("<Enter>")
|
||||
self.unbind("<Leave>")
|
||||
elif state == tk.NORMAL:
|
||||
self.config(cursor="hand2")
|
||||
self.bind("<Button-1>", self._on_click)
|
||||
self.bind("<Enter>", self._on_enter)
|
||||
self.bind("<Leave>", self._on_leave)
|
||||
|
||||
def set_progress(self, percent):
|
||||
self.progress = percent
|
||||
self._update_layout()
|
||||
|
||||
class BatchTableExtractorApp:
|
||||
def __init__(self, root):
|
||||
self.root = root
|
||||
self.root.title("Word 表格全量批量导出工具 (Office/WPS 通用版)")
|
||||
self.root.title("WordTableExtractor")
|
||||
self.root.geometry("640x520")
|
||||
self.root.minsize(580, 460)
|
||||
|
||||
@@ -23,8 +84,17 @@ class BatchTableExtractorApp:
|
||||
self.out_dir_var = tk.StringVar()
|
||||
self.recursive_var = tk.BooleanVar(value=False)
|
||||
self.auto_extract_var = tk.BooleanVar(value=False)
|
||||
self.debug_var = tk.BooleanVar(value=False)
|
||||
self.topmost_var = tk.BooleanVar(value=False)
|
||||
self.conflict_action_var = tk.StringVar(value="直接覆盖 (默认)")
|
||||
|
||||
import threading
|
||||
self._stop_event = threading.Event()
|
||||
self._pause_event = threading.Event()
|
||||
self._is_running = False
|
||||
|
||||
self._load_config()
|
||||
self.root.attributes("-topmost", self.topmost_var.get())
|
||||
self._build_ui()
|
||||
self._on_mode_change()
|
||||
|
||||
@@ -48,6 +118,9 @@ class BatchTableExtractorApp:
|
||||
self.out_dir_var.set(cfg.get("out_dir", ""))
|
||||
self.recursive_var.set(cfg.get("recursive", False))
|
||||
self.auto_extract_var.set(cfg.get("auto_extract", False))
|
||||
self.debug_var.set(cfg.get("debug_mode", False))
|
||||
self.topmost_var.set(cfg.get("topmost", False))
|
||||
self.conflict_action_var.set(cfg.get("conflict_action", "直接覆盖 (默认)"))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -58,7 +131,10 @@ class BatchTableExtractorApp:
|
||||
"src_path": self.src_path_var.get(),
|
||||
"out_dir": self.out_dir_var.get(),
|
||||
"recursive": self.recursive_var.get(),
|
||||
"auto_extract": self.auto_extract_var.get()
|
||||
"auto_extract": self.auto_extract_var.get(),
|
||||
"debug_mode": self.debug_var.get(),
|
||||
"topmost": self.topmost_var.get(),
|
||||
"conflict_action": self.conflict_action_var.get()
|
||||
}
|
||||
try:
|
||||
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
||||
@@ -74,15 +150,25 @@ class BatchTableExtractorApp:
|
||||
mode_box = ttk.LabelFrame(frame, text=" 处理模式 ", padding="8")
|
||||
mode_box.pack(fill=tk.X, pady=(0, 10))
|
||||
|
||||
# 配置列权重以实现更好的分布
|
||||
mode_box.columnconfigure(0, weight=1)
|
||||
mode_box.columnconfigure(1, weight=1)
|
||||
mode_box.columnconfigure(2, weight=1)
|
||||
|
||||
ttk.Radiobutton(mode_box, text="批量处理文件夹", variable=self.mode_var, value="dir",
|
||||
command=self._on_mode_change).pack(side=tk.LEFT, padx=15)
|
||||
command=self._on_mode_change, takefocus=False).grid(row=0, column=0, sticky=tk.W, padx=10, pady=2)
|
||||
ttk.Radiobutton(mode_box, text="处理单个文件", variable=self.mode_var, value="file",
|
||||
command=self._on_mode_change).pack(side=tk.LEFT, padx=15)
|
||||
self.chk_recursive = ttk.Checkbutton(mode_box, text="包含子文件夹", variable=self.recursive_var)
|
||||
self.chk_recursive.pack(side=tk.RIGHT, padx=10)
|
||||
command=self._on_mode_change, takefocus=False).grid(row=0, column=1, sticky=tk.W, padx=10, pady=2)
|
||||
self.chk_recursive = ttk.Checkbutton(mode_box, text="包含子文件夹", variable=self.recursive_var, takefocus=False)
|
||||
self.chk_recursive.grid(row=0, column=2, sticky=tk.W, padx=10, pady=2)
|
||||
|
||||
self.chk_auto_extract = ttk.Checkbutton(mode_box, text="拖拽后立即提取", variable=self.auto_extract_var)
|
||||
self.chk_auto_extract.pack(side=tk.RIGHT, padx=10)
|
||||
self.chk_debug = ttk.Checkbutton(mode_box, text="DEBUG", variable=self.debug_var, command=self._on_debug_toggle, takefocus=False)
|
||||
self.chk_debug.grid(row=1, column=0, sticky=tk.W, padx=10, pady=2)
|
||||
self.chk_auto_extract = ttk.Checkbutton(mode_box, text="拖拽后立即提取", variable=self.auto_extract_var, takefocus=False)
|
||||
self.chk_auto_extract.grid(row=1, column=1, sticky=tk.W, padx=10, pady=2)
|
||||
|
||||
self.chk_topmost = ttk.Checkbutton(mode_box, text="窗口置顶", variable=self.topmost_var, command=self._on_topmost_toggle, takefocus=False)
|
||||
self.chk_topmost.grid(row=1, column=2, sticky=tk.W, padx=10, pady=2)
|
||||
|
||||
# 2. 路径配置
|
||||
path_box = ttk.LabelFrame(frame, text=" 路径设置 ", padding="10")
|
||||
@@ -91,21 +177,28 @@ class BatchTableExtractorApp:
|
||||
self.lbl_src = ttk.Label(path_box, text="来源目录:")
|
||||
self.lbl_src.grid(row=0, column=0, sticky=tk.W, pady=5)
|
||||
ttk.Entry(path_box, textvariable=self.src_path_var, width=46).grid(row=0, column=1, sticky=tk.EW, padx=6)
|
||||
self.btn_browse_src = ttk.Button(path_box, text="选择...", command=self._browse_src)
|
||||
self.btn_browse_src.grid(row=0, column=2)
|
||||
self.btn_browse_src = ProgressButton(path_box, text="选择...", command=self._browse_src, height=22, width=65)
|
||||
self.btn_browse_src.grid(row=0, column=2, sticky=tk.EW)
|
||||
|
||||
ttk.Label(path_box, text="导出目录:").grid(row=1, column=0, sticky=tk.W, pady=5)
|
||||
ttk.Entry(path_box, textvariable=self.out_dir_var, width=46, state="readonly").grid(row=1, column=1, sticky=tk.EW, padx=6)
|
||||
ttk.Button(path_box, text="选择...", command=self._browse_out).grid(row=1, column=2)
|
||||
self.btn_browse_out = ProgressButton(path_box, text="选择...", command=self._browse_out, height=22, width=65)
|
||||
self.btn_browse_out.grid(row=1, column=2, sticky=tk.EW)
|
||||
|
||||
ttk.Label(path_box, text="遇到同名文件:").grid(row=2, column=0, sticky=tk.W, pady=5)
|
||||
ttk.Combobox(path_box, textvariable=self.conflict_action_var, values=["直接覆盖 (默认)", "自动重命名", "直接跳过"], state="readonly", width=43).grid(row=2, column=1, sticky=tk.W, padx=6)
|
||||
|
||||
self.btn_view_log = ProgressButton(path_box, text="日志", command=self._show_log_window, height=22, width=65)
|
||||
self.btn_view_log.grid(row=2, column=2, sticky=tk.EW)
|
||||
|
||||
path_box.columnconfigure(1, weight=1)
|
||||
|
||||
# 3. 运行操作区
|
||||
self.btn_run = ttk.Button(frame, text="开始全量提取表格", command=self._start)
|
||||
self.btn_run.pack(fill=tk.X, ipady=5, pady=(0, 8))
|
||||
|
||||
self.bar = ttk.Progressbar(frame, mode='determinate')
|
||||
self.bar.pack(fill=tk.X, pady=(0, 10))
|
||||
btn_frame = ttk.Frame(frame)
|
||||
btn_frame.pack(fill=tk.X, pady=(0, 10))
|
||||
|
||||
self.btn_run = ProgressButton(btn_frame, text="开始全量提取表格", command=self._start)
|
||||
self.btn_run.pack(side=tk.LEFT, fill=tk.X, expand=True)
|
||||
|
||||
# 4. 运行日志窗口
|
||||
log_box = ttk.LabelFrame(frame, text=" 运行日志 ", padding="8")
|
||||
@@ -117,6 +210,22 @@ class BatchTableExtractorApp:
|
||||
sb.pack(side=tk.RIGHT, fill=tk.Y)
|
||||
self.txt.config(yscrollcommand=sb.set)
|
||||
|
||||
def _on_debug_toggle(self):
|
||||
if self.debug_var.get():
|
||||
messagebox.showinfo("Debug 模式说明", "开启 Debug 模式后,程序在提取表格时将强制显示 Office/WPS 窗口。\n\n这主要用于排查程序“卡死”的问题。例如:当文档被加密或需要修复时,Office 会在后台弹窗等待用户点击。开启此模式可让你看到这些弹窗并手动处理。")
|
||||
|
||||
def _on_topmost_toggle(self):
|
||||
self.root.attributes("-topmost", self.topmost_var.get())
|
||||
|
||||
def _stop_task(self):
|
||||
self._pause_event.set()
|
||||
ans = messagebox.askyesno("确认", "任务已暂停。\n\n是否确定终止批量提取操作?\n(选择“是”终止操作,选择“否”继续提取)")
|
||||
if ans:
|
||||
self._stop_event.set()
|
||||
self.btn_run.config_btn(state=tk.DISABLED, text="正在终止...")
|
||||
self.log("\n⚠️ 正在尝试终止任务,请等待当前文件处理完毕...")
|
||||
self._pause_event.clear()
|
||||
|
||||
def _on_mode_change(self):
|
||||
if self.mode_var.get() == "dir":
|
||||
self.lbl_src.config(text="来源目录:")
|
||||
@@ -159,6 +268,9 @@ class BatchTableExtractorApp:
|
||||
if not dropped_paths:
|
||||
return
|
||||
|
||||
if len(dropped_paths) > 1:
|
||||
messagebox.showinfo("提示", "目前仅支持单次拖拽一个文件或文件夹。系统将仅读取拖入的第一个项目!")
|
||||
|
||||
first_path = dropped_paths[0]
|
||||
|
||||
if os.path.isdir(first_path):
|
||||
@@ -177,11 +289,152 @@ class BatchTableExtractorApp:
|
||||
if self.auto_extract_var.get():
|
||||
self.root.after(100, self._start)
|
||||
|
||||
def log(self, msg):
|
||||
self.txt.insert(tk.END, f"{msg}\n")
|
||||
def record_log(self, batch_id, status, doc_name, excel_name, table_count, duration, src_path, message):
|
||||
log_path = os.path.join(APP_DIR, "conversion.csv")
|
||||
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
try:
|
||||
file_exists = os.path.exists(log_path)
|
||||
import csv
|
||||
with open(log_path, "a", encoding="utf-8-sig", newline="") as f:
|
||||
writer = csv.writer(f)
|
||||
if not file_exists:
|
||||
writer.writerow(["任务批次", "处理时间", "耗时(秒)", "来源文档", "导出文件", "表格数量", "处理状态", "原文档路径", "备注详情"])
|
||||
writer.writerow([batch_id, now, f"{duration:.3f}", doc_name, excel_name, str(table_count), status, src_path, message])
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _show_log_window(self):
|
||||
log_path = os.path.join(APP_DIR, "conversion.csv")
|
||||
if not os.path.exists(log_path):
|
||||
messagebox.showinfo("提示", "目前还没有历史日志。")
|
||||
return
|
||||
|
||||
win = tk.Toplevel(self.root)
|
||||
win.title("历史转换日志")
|
||||
win.geometry("900x500")
|
||||
if self.topmost_var.get():
|
||||
win.attributes("-topmost", True)
|
||||
|
||||
filter_frame = ttk.Frame(win, padding=10)
|
||||
filter_frame.pack(fill=tk.X)
|
||||
|
||||
ttk.Label(filter_frame, text="按状态筛选:").pack(side=tk.LEFT)
|
||||
filter_var = tk.StringVar(value="全部")
|
||||
filter_cb = ttk.Combobox(filter_frame, textvariable=filter_var, values=["全部", "仅成功", "仅失败/跳过"], state="readonly", width=15)
|
||||
filter_cb.pack(side=tk.LEFT, padx=10)
|
||||
|
||||
columns = ("batch", "time", "duration", "doc", "excel", "tables", "status", "path", "msg")
|
||||
tree = ttk.Treeview(win, columns=columns, show="headings")
|
||||
|
||||
def sort_treeview(tv, col, reverse):
|
||||
l = [(tv.set(k, col), k) for k in tv.get_children('')]
|
||||
def convert(val):
|
||||
try: return float(val)
|
||||
except ValueError: return val
|
||||
l.sort(key=lambda t: convert(t[0]), reverse=reverse)
|
||||
for index, (val, k) in enumerate(l):
|
||||
tv.move(k, '', index)
|
||||
tv.heading(col, command=lambda: sort_treeview(tv, col, not reverse))
|
||||
|
||||
headers = {
|
||||
"batch": ("任务批次", 100, tk.CENTER),
|
||||
"time": ("处理时间", 140, tk.CENTER),
|
||||
"duration": ("耗时", 50, tk.CENTER),
|
||||
"doc": ("来源文档", 130, tk.W),
|
||||
"excel": ("导出文件", 130, tk.W),
|
||||
"tables": ("表格数", 50, tk.CENTER),
|
||||
"status": ("状态", 50, tk.CENTER),
|
||||
"path": ("原文件路径", 180, tk.W),
|
||||
"msg": ("备注详情", 180, tk.W)
|
||||
}
|
||||
|
||||
for col, (text, width, anchor) in headers.items():
|
||||
tree.heading(col, text=text, command=lambda c=col: sort_treeview(tree, c, False))
|
||||
tree.column(col, width=width, anchor=anchor)
|
||||
|
||||
tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
|
||||
sb = ttk.Scrollbar(win, orient=tk.VERTICAL, command=tree.yview)
|
||||
sb.pack(side=tk.RIGHT, fill=tk.Y)
|
||||
tree.config(yscrollcommand=sb.set)
|
||||
|
||||
tree.tag_configure("error", foreground="red")
|
||||
|
||||
import csv
|
||||
with open(log_path, "r", encoding="utf-8-sig") as f:
|
||||
reader = csv.reader(f)
|
||||
header = next(reader, None)
|
||||
all_rows = list(reader)
|
||||
all_rows.reverse() # 倒序排列,最新日志在最前
|
||||
|
||||
def update_log_view(event=None):
|
||||
for item in tree.get_children():
|
||||
tree.delete(item)
|
||||
f_val = filter_var.get()
|
||||
|
||||
for row in all_rows:
|
||||
if len(row) < 6: continue
|
||||
# 如果是旧版日志(6列),需要补全为9列
|
||||
if len(row) == 6:
|
||||
batch, t, doc, exc, status, msg = row
|
||||
dur, tables, pth = "0.0", "0", ""
|
||||
else:
|
||||
batch, t, dur, doc, exc, tables, status, pth, msg = row[:9]
|
||||
|
||||
is_error = status in ("失败", "跳过")
|
||||
is_success = status == "成功"
|
||||
|
||||
if f_val == "仅成功" and not is_success:
|
||||
continue
|
||||
if f_val == "仅失败/跳过" and not is_error:
|
||||
continue
|
||||
|
||||
tag = "error" if is_error else ()
|
||||
tree.insert("", tk.END, values=(batch, t, dur, doc, exc, tables, status, pth, msg), tags=tag)
|
||||
|
||||
filter_cb.bind("<<ComboboxSelected>>", update_log_view)
|
||||
update_log_view()
|
||||
|
||||
def on_double_click(event):
|
||||
item = tree.selection()
|
||||
if not item: return
|
||||
item = item[0]
|
||||
values = tree.item(item, "values")
|
||||
if not values: return
|
||||
msg = values[8]
|
||||
|
||||
detail_win = tk.Toplevel(win)
|
||||
detail_win.title("详细信息")
|
||||
detail_win.geometry("500x300")
|
||||
if self.topmost_var.get():
|
||||
detail_win.attributes("-topmost", True)
|
||||
|
||||
txt = tk.Text(detail_win, wrap=tk.WORD, font=("Consolas", 9))
|
||||
txt.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
|
||||
txt.insert(tk.END, msg)
|
||||
txt.config(state=tk.DISABLED)
|
||||
|
||||
tree.bind("<Double-1>", on_double_click)
|
||||
|
||||
def log(self, msg, tag=None):
|
||||
self.txt.tag_config("error", foreground="red")
|
||||
self.txt.tag_config("highlight", foreground="red")
|
||||
if tag:
|
||||
self.txt.insert(tk.END, f"{msg}\n", tag)
|
||||
elif "跳过" in msg or "❌" in msg or "失败" in msg:
|
||||
self.txt.insert(tk.END, f"{msg}\n", "error")
|
||||
else:
|
||||
self.txt.insert(tk.END, f"{msg}\n")
|
||||
self.txt.see(tk.END)
|
||||
|
||||
def _on_close(self):
|
||||
if getattr(self, '_is_running', False):
|
||||
self._pause_event.set()
|
||||
ans = messagebox.askyesno("确认退出", "当前正在提取表格,强制退出可能会导致部分文件提取不完整。\n\n是否确定要退出程序?")
|
||||
if not ans:
|
||||
self._pause_event.clear()
|
||||
return
|
||||
self._stop_event.set()
|
||||
|
||||
self._save_config()
|
||||
self.root.destroy()
|
||||
|
||||
@@ -228,9 +481,11 @@ class BatchTableExtractorApp:
|
||||
messagebox.showinfo("提示", "未找到任何待处理的 .doc 或 .docx 文件!")
|
||||
return
|
||||
|
||||
self.btn_run.config(state=tk.DISABLED)
|
||||
self.bar['value'] = 0
|
||||
self.bar['maximum'] = len(files_to_process)
|
||||
self.btn_run.config_btn(text="启动中... ", command=self._stop_task)
|
||||
self.btn_run.set_progress(0.0)
|
||||
self._stop_event.clear()
|
||||
self._is_running = True
|
||||
|
||||
self.log(f"\n===== 开始任务: 共扫描到 {len(files_to_process)} 个文件 =====")
|
||||
|
||||
threading.Thread(
|
||||
@@ -239,38 +494,108 @@ class BatchTableExtractorApp:
|
||||
daemon=True
|
||||
).start()
|
||||
|
||||
def _generate_batch_id(self):
|
||||
date_str = datetime.datetime.now().strftime("%y%m%d")
|
||||
log_path = os.path.join(APP_DIR, "conversion.csv")
|
||||
seq = 1
|
||||
if os.path.exists(log_path):
|
||||
try:
|
||||
import csv
|
||||
with open(log_path, "r", encoding="utf-8-sig") as f:
|
||||
reader = csv.reader(f)
|
||||
for row in reader:
|
||||
if row and row[0].startswith(f"{date_str}X"):
|
||||
try:
|
||||
current_seq = int(row[0].split("X")[1])
|
||||
if current_seq >= seq:
|
||||
seq = current_seq + 1
|
||||
except ValueError:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return f"{date_str}X{seq:02d}"
|
||||
|
||||
def _worker(self, file_list, out_dir):
|
||||
pythoncom.CoInitialize()
|
||||
word_app = None
|
||||
excel_app = None
|
||||
success_count = 0
|
||||
batch_id = self._generate_batch_id()
|
||||
|
||||
try:
|
||||
word_app, excel_app, engine_name = detect_and_create_apps()
|
||||
self.root.after(0, lambda: self.log(f"已启动宿主引擎: 【{engine_name}】"))
|
||||
|
||||
word_app.Visible = False
|
||||
word_app.DisplayAlerts = False
|
||||
excel_app.Visible = False
|
||||
excel_app.DisplayAlerts = False
|
||||
debug_mode = self.debug_var.get()
|
||||
word_app.Visible = debug_mode
|
||||
word_app.DisplayAlerts = debug_mode
|
||||
excel_app.Visible = debug_mode
|
||||
excel_app.DisplayAlerts = debug_mode
|
||||
|
||||
total = len(file_list)
|
||||
for idx, file_path in enumerate(file_list, start=1):
|
||||
if self._pause_event.is_set():
|
||||
self.root.after(0, lambda: self.btn_run.config_btn(text="任务已暂停..."))
|
||||
import time
|
||||
while self._pause_event.is_set():
|
||||
time.sleep(0.1)
|
||||
|
||||
if self._stop_event.is_set():
|
||||
self.root.after(0, lambda: self.log("\n❌ 任务已被用户手动终止!"))
|
||||
break
|
||||
|
||||
base_name = os.path.splitext(os.path.basename(file_path))[0]
|
||||
target_excel = os.path.join(out_dir, f"{base_name}_表格.xlsx")
|
||||
|
||||
conflict_action = self.conflict_action_var.get()
|
||||
if os.path.exists(target_excel):
|
||||
if conflict_action == "直接跳过":
|
||||
self.root.after(0, lambda i=idx, t=total, name=base_name: self.log(f"[{i}/{t}] 跳过同名: {name}"))
|
||||
self.record_log(batch_id, "跳过", base_name, "-", 0, 0.0, file_path, "发现同名文件,跳过")
|
||||
def update_skip_btn(i=idx, t=total):
|
||||
self.btn_run.config_btn(text=f"提取中 {i}/{t} | 点击终止操作")
|
||||
self.btn_run.set_progress(i / t)
|
||||
self.root.after(0, update_skip_btn)
|
||||
continue
|
||||
elif conflict_action == "自动重命名":
|
||||
counter = 1
|
||||
while True:
|
||||
new_name = f"{base_name}_表格_{counter}.xlsx"
|
||||
target_excel = os.path.join(out_dir, new_name)
|
||||
if not os.path.exists(target_excel):
|
||||
break
|
||||
counter += 1
|
||||
|
||||
self.root.after(0, lambda i=idx, t=total, name=base_name: self.log(f"[{i}/{t}] 处理中: {name}"))
|
||||
import time
|
||||
t0 = time.time()
|
||||
try:
|
||||
if export_single_doc_tables(word_app, excel_app, file_path, target_excel,
|
||||
log_func=lambda m: self.root.after(0, self.log, m)):
|
||||
def my_log(m):
|
||||
self.root.after(0, self.log, m)
|
||||
|
||||
tc = export_single_doc_tables(word_app, excel_app, file_path, target_excel,
|
||||
log_func=my_log, debug=debug_mode)
|
||||
duration = time.time() - t0
|
||||
if tc > 0:
|
||||
success_count += 1
|
||||
self.record_log(batch_id, "成功", base_name, f"{base_name}_表格.xlsx", tc, duration, file_path, "提取完成")
|
||||
else:
|
||||
self.record_log(batch_id, "跳过", base_name, "-", 0, duration, file_path, "未检测到表格")
|
||||
except Exception as e:
|
||||
self.root.after(0, lambda n=base_name, err=str(e): self.log(f" ❌ 出错跳过 [{n}]: {err}"))
|
||||
duration = time.time() - t0
|
||||
import traceback
|
||||
trace_str = traceback.format_exc()
|
||||
err_msg = f" ❌ 失败跳过 [{base_name}]: {e}"
|
||||
self.root.after(0, lambda m=err_msg: self.log(m))
|
||||
self.record_log(batch_id, "失败", base_name, "-", 0, duration, file_path, f"{e}\n{trace_str}")
|
||||
|
||||
# 更新进度条
|
||||
self.root.after(0, lambda val=idx: self.bar.configure(value=val))
|
||||
# 更新按钮文字进度
|
||||
def update_btn(i=idx, t=total):
|
||||
self.btn_run.config_btn(text=f"提取中 {i}/{t} | 点击终止操作")
|
||||
self.btn_run.set_progress(i / t)
|
||||
self.root.after(0, update_btn)
|
||||
|
||||
self.root.after(0, lambda: self.log(f"===== 处理完成!成功导出 {success_count}/{total} 个文档的表格 ====="))
|
||||
self.root.after(0, lambda: self.log(f"\n===== 处理完成!成功导出 {success_count}/{total} 个文档的表格 =====\n", tag="highlight"))
|
||||
self.root.after(0, lambda: messagebox.showinfo("批量完成", f"处理完成!\n成功提取: {success_count}/{total} 个文件。"))
|
||||
|
||||
except Exception as e:
|
||||
@@ -288,4 +613,8 @@ class BatchTableExtractorApp:
|
||||
except Exception:
|
||||
pass
|
||||
pythoncom.CoUninitialize()
|
||||
self.root.after(0, lambda: self.btn_run.config(state=tk.NORMAL))
|
||||
def _reset_btn():
|
||||
self.btn_run.config_btn(state=tk.NORMAL, text="开始全量提取表格", command=self._start)
|
||||
self.btn_run.set_progress(0.0)
|
||||
self._is_running = False
|
||||
self.root.after(0, _reset_btn)
|
||||
|
||||
Reference in New Issue
Block a user