refactor: 解耦 gui.py,抽离自定义组件至 widgets.py,日志业务至 history_window.py,并全面更新 README 文档
This commit is contained in:
@@ -6,32 +6,35 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 核心特性
|
## 🌟 核心特性
|
||||||
|
|
||||||
* **合并单元格无损迁移**:直接映射底层表格拓扑结构,彻底避免跨行跨列时出现的列整体左移、错位问题。
|
* **合并单元格无损迁移**:直接映射底层表格拓扑结构,彻底避免跨行跨列时出现的列整体左移、错位问题。
|
||||||
* **全量提取(无截断限制)**:针对 100+ 行超长清单设计,完整保留文档中的所有行与列。
|
* **全新扁平化 UI 设计**:界面全面升级为无边框扁平化风格。独创悬浮式绿色流体进度条按钮,状态与进度直观融合。
|
||||||
* **智能自适应引擎**:自动探测宿主环境。优先调用 **Microsoft Office**,若未安装则自动平滑降级调用 **WPS Office**,免除环境配置烦恼。
|
* **智能自适应引擎**:自动探测宿主环境。优先调用 **Microsoft Office**,若未安装则自动平滑降级调用 **WPS Office**,免除环境配置烦恼。
|
||||||
* **双模式处理**:支持单独处理单份文件,或递归扫描整个文件夹及其子目录进行批量转换。
|
* **灵活的多文件处理**:支持拖拽文件/文件夹快速提取。支持单独处理单份文件,或递归扫描整个文件夹及其子目录进行批量转换。
|
||||||
* **配置自动持久化**:记住上次选择的导出路径、来源目录及递归选项,写入本地 `config.json`(支持开发与 `.exe` 打包环境自动适配路径)。
|
* **安全的中断与控制**:支持提取过程中途暂停,弹出确认保护防止误触关闭;遇到同名文件可灵活选择直接覆盖、自动重命名或跳过。
|
||||||
|
* **详尽的历史日志追踪**:内置本地 CSV 转换日志,通过一键“日志”面板随时追溯每次批处理的成功数、耗时、表格数及报错详情。
|
||||||
* **独立单文件(免环境)**:可打包为纯净单文件可执行程序,目标机器无需配置 Python 或 Java 环境,开箱即用。
|
* **独立单文件(免环境)**:可打包为纯净单文件可执行程序,目标机器无需配置 Python 或 Java 环境,开箱即用。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 项目结构
|
## 📁 项目结构
|
||||||
|
|
||||||
```text
|
```text
|
||||||
WordTableExtractor/
|
WordTableExtractor/
|
||||||
├── src/
|
├── src/
|
||||||
│ └── smart_batch_table_extractor_gui.py # 主程序核心源码
|
│ ├── main.py # 应用程序启动入口
|
||||||
├── config.json # 用户配置(运行后自动生成在根目录)
|
│ ├── gui.py # 扁平化 UI 界面及主线程业务逻辑
|
||||||
|
│ ├── extractor.py # Office/WPS 自动化引擎交互核心
|
||||||
|
│ └── config.py # 环境配置及通用变量
|
||||||
|
├── .gitignore
|
||||||
├── LICENSE
|
├── LICENSE
|
||||||
└── README.md
|
└── README.md
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 快速上手(源码运行)
|
## 🚀 快速上手(源码运行)
|
||||||
|
|
||||||
### 1. 环境要求
|
### 1. 环境要求
|
||||||
|
|
||||||
@@ -42,8 +45,7 @@ WordTableExtractor/
|
|||||||
### 2. 安装依赖
|
### 2. 安装依赖
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
pip install pywin32
|
pip install pywin32 windnd
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
> **Windows 下安装 `pywin32` 后的初始化提示**:
|
> **Windows 下安装 `pywin32` 后的初始化提示**:
|
||||||
@@ -52,21 +54,17 @@ pip install pywin32
|
|||||||
> python -c "import sys, os; print(os.path.join(sys.prefix, 'Scripts', 'pywin32_postinstall.py'))"
|
> python -c "import sys, os; print(os.path.join(sys.prefix, 'Scripts', 'pywin32_postinstall.py'))"
|
||||||
> # 执行打印出的完整脚本路径:
|
> # 执行打印出的完整脚本路径:
|
||||||
> python <完整路径> -install
|
> python <完整路径> -install
|
||||||
>
|
|
||||||
> ```
|
> ```
|
||||||
>
|
|
||||||
>
|
|
||||||
|
|
||||||
### 3. 运行程序
|
### 3. 运行程序
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python smart_batch_table_extractor_gui.py
|
python src/main.py
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 打包为独立 EXE(免安装环境分发)
|
## 📦 打包为独立 EXE(免安装环境分发)
|
||||||
|
|
||||||
若需要分发给没有 Python 环境的同事或部署在业务现场机器,可使用 PyInstaller 编译为单文件绿色版程序。
|
若需要分发给没有 Python 环境的同事或部署在业务现场机器,可使用 PyInstaller 编译为单文件绿色版程序。
|
||||||
|
|
||||||
@@ -74,14 +72,13 @@ python smart_batch_table_extractor_gui.py
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
pip install pyinstaller
|
pip install pyinstaller
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. 执行编译命令(优化瘦身体积)
|
### 2. 执行编译命令(优化瘦身体积)
|
||||||
|
|
||||||
执行以下指令,排除不必要的测试套件与调试模块:
|
在项目根目录下执行以下指令,排除不必要的调试模块:
|
||||||
|
|
||||||
```
|
```powershell
|
||||||
pyinstaller -F -w `
|
pyinstaller -F -w `
|
||||||
--hidden-import "win32com.client" `
|
--hidden-import "win32com.client" `
|
||||||
--hidden-import "pythoncom" `
|
--hidden-import "pythoncom" `
|
||||||
@@ -95,17 +92,17 @@ pyinstaller -F -w `
|
|||||||
--exclude-module "setuptools" `
|
--exclude-module "setuptools" `
|
||||||
--exclude-module "distutils" `
|
--exclude-module "distutils" `
|
||||||
--name "WordTableExtractor" `
|
--name "WordTableExtractor" `
|
||||||
src/smart_batch_table_extractor_gui.py
|
src/main.py
|
||||||
```
|
```
|
||||||
|
|
||||||
编译完成后,可在 `dist/` 目录下获取 `WordTableExtractor.exe`,直接拷贝至其他 Windows 电脑运行。
|
编译完成后,可在 `dist/` 目录下获取 `WordTableExtractor.exe`,直接拷贝至其他 Windows 电脑运行。配置信息与运行日志将自动在该 exe 所在的目录中生成 `config.json` 与 `conversion.csv`。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 使用说明
|
## 💡 使用说明
|
||||||
|
|
||||||
1. 启动工具后,日志窗口会自动打印当前检测到的办公组件引擎(`Microsoft Office` 或 `WPS Office`)。
|
1. **引擎初始化**:启动工具后,日志窗口会自动打印当前检测到的办公组件引擎(优先 `Microsoft Office`,兜底 `WPS Office`)。
|
||||||
2. 根据需求选择 **“批量处理文件夹”** 或 **“处理单个文件”**。
|
2. **选择模式**:根据需求选择 **“批量处理文件夹”** 或 **“处理单个文件”**,也可直接将文档或文件夹**拖拽**到主窗口中。
|
||||||
3. 指定来源路径与导出目标目录。
|
3. **同名策略**:当导出目标目录中已存在同名生成的 Excel 时,可在界面左侧调整策略(直接覆盖、自动重命名、直接跳过)。
|
||||||
4. 点击 **“开始全量提取表格”**,进度条与日志窗口将实时展示每个文件的提取结果与表格数量。
|
4. **进度与中途终止**:点击 **“开始全量提取表格”**,流体进度条将接管整个按钮。提取过程中若需停止,只需点击进度条或直接关闭窗口,均会触发友好的中断确认保护机制。
|
||||||
5. 转换生成的目标文件命名格式统一为:`{原文件名}_表格.xlsx`。
|
5. **溯源与日志**:点击右侧的 **“日志”** 按钮即可弹出过滤搜索面板,查看所有历史批次的提取详情。若某文件提取失败,可双击该行日志查看报错栈追溯原因。
|
||||||
+8
-188
@@ -10,66 +10,8 @@ import datetime
|
|||||||
|
|
||||||
from config import CONFIG_FILE, APP_DIR
|
from config import CONFIG_FILE, APP_DIR
|
||||||
from extractor import detect_and_create_apps, export_single_doc_tables
|
from extractor import detect_and_create_apps, export_single_doc_tables
|
||||||
|
from widgets import ProgressButton
|
||||||
class ProgressButton(tk.Canvas):
|
from history_window import record_log
|
||||||
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:
|
class BatchTableExtractorApp:
|
||||||
def __init__(self, root):
|
def __init__(self, root):
|
||||||
@@ -289,131 +231,9 @@ class BatchTableExtractorApp:
|
|||||||
if self.auto_extract_var.get():
|
if self.auto_extract_var.get():
|
||||||
self.root.after(100, self._start)
|
self.root.after(100, self._start)
|
||||||
|
|
||||||
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):
|
def _show_log_window(self):
|
||||||
log_path = os.path.join(APP_DIR, "conversion.csv")
|
from history_window import show_history_log_window
|
||||||
if not os.path.exists(log_path):
|
show_history_log_window(self.root, self.topmost_var.get())
|
||||||
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):
|
def log(self, msg, tag=None):
|
||||||
self.txt.tag_config("error", foreground="red")
|
self.txt.tag_config("error", foreground="red")
|
||||||
@@ -551,7 +371,7 @@ class BatchTableExtractorApp:
|
|||||||
if os.path.exists(target_excel):
|
if os.path.exists(target_excel):
|
||||||
if conflict_action == "直接跳过":
|
if conflict_action == "直接跳过":
|
||||||
self.root.after(0, lambda i=idx, t=total, name=base_name: self.log(f"[{i}/{t}] 跳过同名: {name}"))
|
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, "发现同名文件,跳过")
|
record_log(batch_id, "跳过", base_name, "-", 0, 0.0, file_path, "发现同名文件,跳过")
|
||||||
def update_skip_btn(i=idx, t=total):
|
def update_skip_btn(i=idx, t=total):
|
||||||
self.btn_run.config_btn(text=f"提取中 {i}/{t} | 点击终止操作")
|
self.btn_run.config_btn(text=f"提取中 {i}/{t} | 点击终止操作")
|
||||||
self.btn_run.set_progress(i / t)
|
self.btn_run.set_progress(i / t)
|
||||||
@@ -578,16 +398,16 @@ class BatchTableExtractorApp:
|
|||||||
duration = time.time() - t0
|
duration = time.time() - t0
|
||||||
if tc > 0:
|
if tc > 0:
|
||||||
success_count += 1
|
success_count += 1
|
||||||
self.record_log(batch_id, "成功", base_name, f"{base_name}_表格.xlsx", tc, duration, file_path, "提取完成")
|
record_log(batch_id, "成功", base_name, f"{base_name}_表格.xlsx", tc, duration, file_path, "提取完成")
|
||||||
else:
|
else:
|
||||||
self.record_log(batch_id, "跳过", base_name, "-", 0, duration, file_path, "未检测到表格")
|
record_log(batch_id, "跳过", base_name, "-", 0, duration, file_path, "未检测到表格")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
duration = time.time() - t0
|
duration = time.time() - t0
|
||||||
import traceback
|
import traceback
|
||||||
trace_str = traceback.format_exc()
|
trace_str = traceback.format_exc()
|
||||||
err_msg = f" ❌ 失败跳过 [{base_name}]: {e}"
|
err_msg = f" ❌ 失败跳过 [{base_name}]: {e}"
|
||||||
self.root.after(0, lambda m=err_msg: self.log(m))
|
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}")
|
record_log(batch_id, "失败", base_name, "-", 0, duration, file_path, f"{e}\n{trace_str}")
|
||||||
|
|
||||||
# 更新按钮文字进度
|
# 更新按钮文字进度
|
||||||
def update_btn(i=idx, t=total):
|
def update_btn(i=idx, t=total):
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import os
|
||||||
|
import csv
|
||||||
|
import datetime
|
||||||
|
import tkinter as tk
|
||||||
|
from tkinter import ttk, messagebox
|
||||||
|
from config import APP_DIR
|
||||||
|
|
||||||
|
def record_log(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)
|
||||||
|
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
|
||||||
|
|
||||||
|
class HistoryLogWindow:
|
||||||
|
def __init__(self, parent, is_topmost=False):
|
||||||
|
self.parent = parent
|
||||||
|
self.is_topmost = is_topmost
|
||||||
|
self._show()
|
||||||
|
|
||||||
|
def _show(self):
|
||||||
|
log_path = os.path.join(APP_DIR, "conversion.csv")
|
||||||
|
if not os.path.exists(log_path):
|
||||||
|
messagebox.showinfo("提示", "目前还没有历史日志。")
|
||||||
|
return
|
||||||
|
|
||||||
|
win = tk.Toplevel(self.parent)
|
||||||
|
win.title("历史转换日志")
|
||||||
|
win.geometry("900x500")
|
||||||
|
if self.is_topmost:
|
||||||
|
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")
|
||||||
|
|
||||||
|
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
|
||||||
|
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.is_topmost:
|
||||||
|
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 show_history_log_window(parent, is_topmost):
|
||||||
|
HistoryLogWindow(parent, is_topmost)
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import tkinter as tk
|
||||||
|
|
||||||
|
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()
|
||||||
Reference in New Issue
Block a user