Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c4a24790d6 | ||
|
|
4a7e170e6a | ||
|
|
c1e0677cf8 | ||
|
|
b9d3482905 | ||
|
|
d582dd5410 | ||
|
|
ba1da8d7bd | ||
|
|
a8ec26e58c | ||
|
|
49c04a231a |
@@ -0,0 +1,15 @@
|
|||||||
|
# WordTableExtractor 项目开发规范 (Agent Rules)
|
||||||
|
|
||||||
|
这是一份供 AI Assistant (Agent) 读取的项目级约束规则文件。
|
||||||
|
|
||||||
|
## 1. 代码提交流程 (Git Commits)
|
||||||
|
- **必须使用中文**编写 Git Commit Message。
|
||||||
|
- 每次修改完代码并测试通过后,请养成主动提交代码的习惯,并遵循约定式提交规范(例如:`feat: 增加xxx功能`, `fix: 修复xxx问题`, `docs: 更新文档` 等)。
|
||||||
|
|
||||||
|
## 2. 核心架构约束 (Core Architecture)
|
||||||
|
- **禁止使用 Office COM (win32com) 进行常规的数据提取**。
|
||||||
|
- 必须使用 `python-docx` 读取 Word 文档,使用 `openpyxl` 和 `pandas` 写入 Excel。这是为了保证程序在后台绝对静默运行,不弹出窗口,不抢夺用户焦点。
|
||||||
|
- `win32.DispatchEx` 仅在极少数必须进行前置格式转换(如 `.doc` 转 `.docx`)且没有其他替代方案时才能作为 fallback 使用,并且必须保证 `Visible = False`。
|
||||||
|
|
||||||
|
## 3. UI 交互规范
|
||||||
|
- 点击“开始提取”或拖拽文件时,必须第一时间清空日志窗口,确保运行日志清爽。
|
||||||
@@ -1,2 +1,5 @@
|
|||||||
pywin32
|
pywin32
|
||||||
windnd
|
windnd
|
||||||
|
python-docx
|
||||||
|
openpyxl
|
||||||
|
pandas
|
||||||
|
|||||||
+116
-124
@@ -2,157 +2,149 @@ import os
|
|||||||
import pythoncom
|
import pythoncom
|
||||||
import win32com.client as win32
|
import win32com.client as win32
|
||||||
|
|
||||||
def detect_and_create_apps(engine_choice="自动判断 (推荐)"):
|
def convert_doc_to_docx(doc_path, log_func=None, debug=False):
|
||||||
"""探测并绑定 Microsoft Office 或 WPS 引擎"""
|
"""
|
||||||
|
静默将 .doc 转换为 .docx,不影响用户已打开的任何 Word 文档。
|
||||||
|
使用独立进程 (DispatchEx) 和只读模式 (ReadOnly=True)。
|
||||||
|
"""
|
||||||
|
import tempfile
|
||||||
|
import pythoncom
|
||||||
|
|
||||||
def try_ms_office():
|
pythoncom.CoInitialize()
|
||||||
try:
|
word_app = None
|
||||||
word = win32.gencache.EnsureDispatch('Word.Application')
|
|
||||||
excel = win32.gencache.EnsureDispatch('Excel.Application')
|
|
||||||
return word, excel, "Microsoft Office"
|
|
||||||
except Exception:
|
|
||||||
try:
|
|
||||||
word = win32.Dispatch('Word.Application')
|
|
||||||
excel = win32.Dispatch('Excel.Application')
|
|
||||||
return word, excel, "Microsoft Office"
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def try_wps():
|
|
||||||
try:
|
|
||||||
try:
|
|
||||||
word = win32.gencache.EnsureDispatch('wps.Application')
|
|
||||||
except Exception:
|
|
||||||
word = win32.Dispatch('kwps.Application')
|
|
||||||
try:
|
|
||||||
excel = win32.gencache.EnsureDispatch('et.Application')
|
|
||||||
except Exception:
|
|
||||||
excel = win32.Dispatch('ket.Application')
|
|
||||||
return word, excel, "WPS Office"
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
if engine_choice == "Microsoft Office":
|
|
||||||
res = try_ms_office()
|
|
||||||
if res: return res
|
|
||||||
raise RuntimeError("未检测到可用的 Microsoft Office!请尝试选择 WPS Office 或 自动判断。")
|
|
||||||
|
|
||||||
elif engine_choice == "WPS Office":
|
|
||||||
res = try_wps()
|
|
||||||
if res: return res
|
|
||||||
raise RuntimeError("未检测到可用的 WPS Office!请尝试选择 Microsoft Office 或 自动判断。")
|
|
||||||
|
|
||||||
else:
|
|
||||||
# 自动判断:先看当前机器上哪个注册表优先,通常按原逻辑
|
|
||||||
res = try_ms_office()
|
|
||||||
if res: return res
|
|
||||||
res = try_wps()
|
|
||||||
if res: return res
|
|
||||||
|
|
||||||
raise RuntimeError("未检测到可用的办公套件!请确保电脑已安装 Microsoft Office 或 WPS。")
|
|
||||||
|
|
||||||
|
|
||||||
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)
|
|
||||||
|
|
||||||
doc = None
|
doc = None
|
||||||
wb = None
|
|
||||||
file_to_clean = None
|
|
||||||
try:
|
try:
|
||||||
if debug and log_func:
|
if debug and log_func:
|
||||||
log_func(f" [Debug] 正在调用 COM 接口打开文档: {abs_doc}")
|
log_func(f" [Debug] 正在启动独立 Word 进程转换 .doc 文件...")
|
||||||
|
|
||||||
|
# 优先尝试启动全新独立的 MS Word 进程
|
||||||
try:
|
try:
|
||||||
doc = word_app.Documents.Open(abs_doc)
|
word_app = win32.DispatchEx('Word.Application')
|
||||||
# 尝试访问属性,如果在“受保护的视图”下,这行会抛出 0x80020009 异常
|
except Exception:
|
||||||
table_count = doc.Tables.Count
|
# 如果没有 MS Word,尝试启动 WPS
|
||||||
except Exception as e:
|
try:
|
||||||
if debug and log_func:
|
word_app = win32.DispatchEx('wps.Application')
|
||||||
log_func(f" [Debug] 访问受阻(可能是受保护的视图),启动智能复制逃逸机制...")
|
except Exception:
|
||||||
out_dir = os.path.dirname(abs_excel)
|
try:
|
||||||
temp_dir = os.path.join(out_dir, "temp")
|
word_app = win32.DispatchEx('kwps.Application')
|
||||||
if not os.path.exists(temp_dir):
|
except Exception:
|
||||||
os.makedirs(temp_dir, exist_ok=True)
|
# 如果当前 WPS 版本不支持 DispatchEx (独立进程),则降级使用普通 Dispatch
|
||||||
file_to_clean = os.path.join(temp_dir, f"~temp_bypass_{os.path.basename(abs_doc)}")
|
try:
|
||||||
|
word_app = win32.Dispatch('wps.Application')
|
||||||
# 使用原生读写剥离 Windows 的 Zone.Identifier (MOTW) 流
|
except Exception:
|
||||||
with open(abs_doc, 'rb') as f_in:
|
word_app = win32.Dispatch('kwps.Application')
|
||||||
with open(file_to_clean, 'wb') as f_out:
|
word_app.Visible = False
|
||||||
f_out.write(f_in.read())
|
word_app.DisplayAlerts = False
|
||||||
|
|
||||||
doc = word_app.Documents.Open(file_to_clean)
|
abs_doc = os.path.abspath(doc_path)
|
||||||
table_count = doc.Tables.Count
|
out_dir = os.path.join(tempfile.gettempdir(), "word_table_extractor_temp")
|
||||||
|
os.makedirs(out_dir, exist_ok=True)
|
||||||
|
|
||||||
|
# 构造临时 docx 路径
|
||||||
|
base_name = os.path.basename(abs_doc)
|
||||||
|
temp_docx = os.path.join(out_dir, f"{base_name}.docx")
|
||||||
|
|
||||||
|
if os.path.exists(temp_docx):
|
||||||
|
try:
|
||||||
|
os.remove(temp_docx)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# ReadOnly=True 是关键,如果文件正在被用户编辑,这样能确保安全读取,不锁定
|
||||||
|
doc = word_app.Documents.Open(abs_doc, ReadOnly=True, Visible=False)
|
||||||
|
|
||||||
|
# 16 = wdFormatDocumentDefault (docx)
|
||||||
|
doc.SaveAs(temp_docx, FileFormat=16)
|
||||||
|
return temp_docx
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
if log_func:
|
||||||
|
log_func(f" [Error] .doc 格式转换失败: {e}")
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
if doc:
|
||||||
|
try:
|
||||||
|
doc.Close(SaveChanges=False)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if word_app:
|
||||||
|
try:
|
||||||
|
word_app.Quit()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
pythoncom.CoUninitialize()
|
||||||
|
|
||||||
|
def export_single_doc_tables(doc_path, excel_path, log_func=None, debug=False):
|
||||||
|
"""
|
||||||
|
提取单个 Word 文件中的所有表格到 Excel。
|
||||||
|
使用 python-docx 和 openpyxl,实现 100% 静默提取。
|
||||||
|
"""
|
||||||
|
from docx import Document
|
||||||
|
from openpyxl import Workbook
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
abs_doc = os.path.abspath(doc_path)
|
||||||
|
abs_excel = os.path.abspath(excel_path)
|
||||||
|
|
||||||
|
file_to_clean = None
|
||||||
|
is_doc = abs_doc.lower().endswith('.doc')
|
||||||
|
|
||||||
|
if is_doc:
|
||||||
|
if debug and log_func:
|
||||||
|
log_func(f" [Info] 检测到旧版 .doc 格式,正在安全转换为 .docx...")
|
||||||
|
abs_doc = convert_doc_to_docx(abs_doc, log_func=log_func, debug=debug)
|
||||||
|
file_to_clean = abs_doc
|
||||||
|
|
||||||
|
try:
|
||||||
|
if debug and log_func:
|
||||||
|
log_func(f" [Debug] 正在使用 python-docx 解析文档...")
|
||||||
|
|
||||||
|
doc = Document(abs_doc)
|
||||||
|
tables = doc.tables
|
||||||
|
table_count = len(tables)
|
||||||
|
|
||||||
if table_count == 0:
|
if table_count == 0:
|
||||||
if log_func:
|
if log_func:
|
||||||
log_func(f" [跳过] 未检测到表格: {os.path.basename(doc_path)}")
|
log_func(f" [跳过] 未检测到表格: {os.path.basename(doc_path)}")
|
||||||
return 0
|
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
|
wb = Workbook()
|
||||||
time.sleep(0.2) # 给系统剪贴板同步数据留点时间
|
wb.remove(wb.active) # 移除默认的Sheet
|
||||||
|
|
||||||
if i > wb.Sheets.Count:
|
for i, table in enumerate(tables):
|
||||||
ws = wb.Sheets.Add(After=wb.Sheets(wb.Sheets.Count))
|
sheet_name = f"Table_{i+1}"
|
||||||
else:
|
ws = wb.create_sheet(title=sheet_name)
|
||||||
ws = wb.Sheets.Item(i)
|
|
||||||
|
|
||||||
ws.Name = f"Table_{i}"
|
|
||||||
|
|
||||||
# Excel的Paste可能会因为剪贴板被占用而报错 0x800A03EC,加入重试机制
|
# python-docx 提取表格数据 (简单遍历,处理了基本的合并单元格结构)
|
||||||
for retry in range(3):
|
for r_idx, row in enumerate(table.rows):
|
||||||
try:
|
row_data = []
|
||||||
ws.Paste()
|
for cell in row.cells:
|
||||||
break
|
row_data.append(cell.text.strip())
|
||||||
except Exception as pe:
|
ws.append(row_data)
|
||||||
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()
|
|
||||||
|
|
||||||
# 51 = xlOpenXMLWorkbook (.xlsx)
|
|
||||||
if os.path.exists(abs_excel):
|
if os.path.exists(abs_excel):
|
||||||
try:
|
try:
|
||||||
os.remove(abs_excel)
|
os.remove(abs_excel)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
wb.SaveAs(Filename=abs_excel, FileFormat=51)
|
wb.save(abs_excel)
|
||||||
|
|
||||||
if log_func:
|
if log_func:
|
||||||
log_func(f" [成功] 提取完成 ({table_count}个表格) -> {os.path.basename(excel_path)}")
|
log_func(f" [成功] 提取完成 ({table_count}个表格) -> {os.path.basename(excel_path)}")
|
||||||
|
|
||||||
return table_count
|
return table_count
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
if log_func:
|
||||||
|
log_func(f" [Error] 提取失败: {e}")
|
||||||
|
raise
|
||||||
finally:
|
finally:
|
||||||
if wb:
|
# 清理 .doc 转换产生的临时文件
|
||||||
try:
|
|
||||||
wb.Close(SaveChanges=False)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
if doc:
|
|
||||||
try:
|
|
||||||
doc.Close(SaveChanges=False)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
if file_to_clean and os.path.exists(file_to_clean):
|
if file_to_clean and os.path.exists(file_to_clean):
|
||||||
try:
|
try:
|
||||||
os.remove(file_to_clean)
|
os.remove(file_to_clean)
|
||||||
temp_dir = os.path.dirname(file_to_clean)
|
|
||||||
if not os.listdir(temp_dir):
|
|
||||||
os.rmdir(temp_dir)
|
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
def export_pdf_image_tables_local(excel_app, file_path, excel_path, pages_str, log_func=None, debug=False):
|
def export_pdf_image_tables_local(excel_app, file_path, excel_path, pages_str, log_func=None, debug=False):
|
||||||
|
|||||||
+52
-75
@@ -10,7 +10,7 @@ import datetime
|
|||||||
import time
|
import time
|
||||||
|
|
||||||
from utils.config import CONFIG_FILE, APP_DIR
|
from utils.config import CONFIG_FILE, APP_DIR
|
||||||
from core.extractor import detect_and_create_apps, export_single_doc_tables
|
from core.extractor import export_single_doc_tables
|
||||||
from ui.widgets import ProgressButton
|
from ui.widgets import ProgressButton
|
||||||
from ui.history_window import record_log
|
from ui.history_window import record_log
|
||||||
|
|
||||||
@@ -44,7 +44,6 @@ class BatchTableExtractorApp:
|
|||||||
self.conflict_action_var = tk.StringVar(value="直接覆盖 (默认)")
|
self.conflict_action_var = tk.StringVar(value="直接覆盖 (默认)")
|
||||||
|
|
||||||
self.pdf_engine_var = tk.StringVar(value="不处理")
|
self.pdf_engine_var = tk.StringVar(value="不处理")
|
||||||
self.engine_var = tk.StringVar(value="自动判断 (推荐)")
|
|
||||||
|
|
||||||
import threading
|
import threading
|
||||||
self._stop_event = threading.Event()
|
self._stop_event = threading.Event()
|
||||||
@@ -95,8 +94,7 @@ class BatchTableExtractorApp:
|
|||||||
"debug_mode": self.debug_var.get(),
|
"debug_mode": self.debug_var.get(),
|
||||||
"topmost": self.topmost_var.get(),
|
"topmost": self.topmost_var.get(),
|
||||||
"conflict_action": self.conflict_action_var.get(),
|
"conflict_action": self.conflict_action_var.get(),
|
||||||
"pdf_engine": self.pdf_engine_var.get(),
|
"pdf_engine": self.pdf_engine_var.get()
|
||||||
"engine_var": self.engine_var.get()
|
|
||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
||||||
@@ -138,11 +136,6 @@ class BatchTableExtractorApp:
|
|||||||
|
|
||||||
self.chk_topmost = ttk.Checkbutton(mode_box, text="窗口置顶", variable=self.topmost_var, command=self._on_topmost_toggle, takefocus=False)
|
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)
|
self.chk_topmost.grid(row=1, column=2, sticky=tk.W, padx=10, pady=2)
|
||||||
|
|
||||||
ttk.Label(mode_box, text="提取引擎:").grid(row=2, column=0, sticky=tk.W, padx=10, pady=2)
|
|
||||||
engine_cb = ttk.Combobox(mode_box, textvariable=self.engine_var, values=["自动判断 (推荐)", "Microsoft Office", "WPS Office"], state="readonly", width=16)
|
|
||||||
engine_cb.grid(row=2, column=1, columnspan=2, sticky=tk.W, padx=10, pady=2)
|
|
||||||
engine_cb.bind("<<ComboboxSelected>>", lambda e: self.root.focus_set())
|
|
||||||
|
|
||||||
# 2. 路径配置
|
# 2. 路径配置
|
||||||
path_box = ttk.LabelFrame(frame, text=" 路径设置 ", padding="10")
|
path_box = ttk.LabelFrame(frame, text=" 路径设置 ", padding="10")
|
||||||
@@ -150,14 +143,18 @@ class BatchTableExtractorApp:
|
|||||||
|
|
||||||
self.lbl_src = ttk.Label(path_box, text="来源目录:")
|
self.lbl_src = ttk.Label(path_box, text="来源目录:")
|
||||||
self.lbl_src.grid(row=0, column=0, sticky=tk.W, pady=5)
|
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)
|
ttk.Entry(path_box, textvariable=self.src_path_var, width=40).grid(row=0, column=1, sticky=tk.EW, padx=6)
|
||||||
self.btn_browse_src = ProgressButton(path_box, text="选择...", command=self._browse_src, height=22, width=65)
|
self.btn_browse_src = ProgressButton(path_box, text="选择...", command=self._browse_src, height=22, width=50)
|
||||||
self.btn_browse_src.grid(row=0, column=2, sticky=tk.EW)
|
self.btn_browse_src.grid(row=0, column=2, sticky=tk.EW, padx=(0, 4))
|
||||||
|
self.btn_open_src = ProgressButton(path_box, text="打开", command=self._open_src_dir, height=22, width=40)
|
||||||
|
self.btn_open_src.grid(row=0, column=3, sticky=tk.EW)
|
||||||
|
|
||||||
ttk.Label(path_box, text="转换目录:").grid(row=1, column=0, sticky=tk.W, pady=5)
|
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.Entry(path_box, textvariable=self.out_dir_var, width=40, state="readonly").grid(row=1, column=1, sticky=tk.EW, padx=6)
|
||||||
self.btn_browse_out = ProgressButton(path_box, text="选择...", command=self._browse_out, height=22, width=65)
|
self.btn_browse_out = ProgressButton(path_box, text="选择...", command=self._browse_out, height=22, width=50)
|
||||||
self.btn_browse_out.grid(row=1, column=2, sticky=tk.EW)
|
self.btn_browse_out.grid(row=1, column=2, sticky=tk.EW, padx=(0, 4))
|
||||||
|
self.btn_open_out = ProgressButton(path_box, text="打开", command=self._open_out_dir, height=22, width=40)
|
||||||
|
self.btn_open_out.grid(row=1, column=3, sticky=tk.EW)
|
||||||
|
|
||||||
ttk.Label(path_box, text="文件冲突:").grid(row=2, column=0, sticky=tk.W, pady=5)
|
ttk.Label(path_box, text="文件冲突:").grid(row=2, column=0, sticky=tk.W, pady=5)
|
||||||
|
|
||||||
@@ -171,14 +168,8 @@ class BatchTableExtractorApp:
|
|||||||
cb_conflict.pack(side=tk.LEFT, fill=tk.X, expand=True)
|
cb_conflict.pack(side=tk.LEFT, fill=tk.X, expand=True)
|
||||||
cb_conflict.bind("<<ComboboxSelected>>", _clear_combo_focus)
|
cb_conflict.bind("<<ComboboxSelected>>", _clear_combo_focus)
|
||||||
|
|
||||||
ttk.Label(combo_frame, text=" PDF: ").pack(side=tk.LEFT)
|
self.btn_view_log = ProgressButton(path_box, text="日志", command=self._show_log_window, height=22, width=94)
|
||||||
|
self.btn_view_log.grid(row=2, column=2, columnspan=2, sticky=tk.EW)
|
||||||
cb_pdf = ttk.Combobox(combo_frame, textvariable=self.pdf_engine_var, values=["智能判定 (推荐)", "强转 Word (极速)", "强制本地 AI (需插件)", "不处理"], state="readonly", width=18)
|
|
||||||
cb_pdf.pack(side=tk.LEFT, fill=tk.X, expand=True)
|
|
||||||
cb_pdf.bind("<<ComboboxSelected>>", _clear_combo_focus)
|
|
||||||
|
|
||||||
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)
|
path_box.columnconfigure(1, weight=1)
|
||||||
|
|
||||||
@@ -247,6 +238,34 @@ class BatchTableExtractorApp:
|
|||||||
if path:
|
if path:
|
||||||
self.out_dir_var.set(os.path.normpath(path))
|
self.out_dir_var.set(os.path.normpath(path))
|
||||||
|
|
||||||
|
def _open_src_dir(self):
|
||||||
|
path = self.src_path_var.get().strip()
|
||||||
|
if not path:
|
||||||
|
messagebox.showinfo("提示", "来源目录为空")
|
||||||
|
return
|
||||||
|
if os.path.isfile(path):
|
||||||
|
path = os.path.dirname(path)
|
||||||
|
if os.path.exists(path):
|
||||||
|
try:
|
||||||
|
os.startfile(path)
|
||||||
|
except Exception as e:
|
||||||
|
messagebox.showerror("错误", f"无法打开目录: {e}")
|
||||||
|
else:
|
||||||
|
messagebox.showinfo("提示", "该来源路径不存在")
|
||||||
|
|
||||||
|
def _open_out_dir(self):
|
||||||
|
path = self.out_dir_var.get().strip()
|
||||||
|
if not path:
|
||||||
|
messagebox.showinfo("提示", "转换目录为空")
|
||||||
|
return
|
||||||
|
if os.path.exists(path):
|
||||||
|
try:
|
||||||
|
os.startfile(path)
|
||||||
|
except Exception as e:
|
||||||
|
messagebox.showerror("错误", f"无法打开目录: {e}")
|
||||||
|
else:
|
||||||
|
messagebox.showinfo("提示", "转换目录目前还不存在,请先提取生成文件")
|
||||||
|
|
||||||
def _on_drop_files(self, files):
|
def _on_drop_files(self, files):
|
||||||
if not files:
|
if not files:
|
||||||
return
|
return
|
||||||
@@ -335,6 +354,9 @@ class BatchTableExtractorApp:
|
|||||||
|
|
||||||
def _start(self):
|
def _start(self):
|
||||||
self._save_config()
|
self._save_config()
|
||||||
|
# 点击提取按钮时,第一时间清空上一次的运行日志
|
||||||
|
self.txt.delete(1.0, tk.END)
|
||||||
|
|
||||||
src = self.src_path_var.get().strip()
|
src = self.src_path_var.get().strip()
|
||||||
out = self.out_dir_var.get().strip()
|
out = self.out_dir_var.get().strip()
|
||||||
mode = self.mode_var.get()
|
mode = self.mode_var.get()
|
||||||
@@ -414,43 +436,8 @@ class BatchTableExtractorApp:
|
|||||||
return f"{date_str}X{seq:02d}"
|
return f"{date_str}X{seq:02d}"
|
||||||
|
|
||||||
def _worker(self, file_list, out_dir):
|
def _worker(self, file_list, out_dir):
|
||||||
pythoncom.CoInitialize()
|
|
||||||
word_app = None
|
|
||||||
excel_app = None
|
|
||||||
apps_initialized = False
|
|
||||||
success_count = 0
|
success_count = 0
|
||||||
batch_id = self._generate_batch_id()
|
batch_id = self._generate_batch_id()
|
||||||
|
|
||||||
def ensure_apps():
|
|
||||||
nonlocal word_app, excel_app, apps_initialized
|
|
||||||
if not apps_initialized:
|
|
||||||
engine_choice = self.engine_var.get()
|
|
||||||
word_app, excel_app, engine_name = detect_and_create_apps(engine_choice)
|
|
||||||
self.root.after(0, lambda: self.log(f"已启动宿主引擎: 【{engine_name}】"))
|
|
||||||
debug_mode = self.debug_var.get()
|
|
||||||
|
|
||||||
# 不要设置 word_app.Visible = False,否则会隐藏用户已经在编辑的其他文档!
|
|
||||||
try:
|
|
||||||
word_app.DisplayAlerts = debug_mode
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
try:
|
|
||||||
word_app.UserControl = True
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# 同理不要设置 excel_app.Visible
|
|
||||||
try:
|
|
||||||
excel_app.DisplayAlerts = debug_mode
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
try:
|
|
||||||
excel_app.UserControl = True
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
apps_initialized = True
|
|
||||||
return word_app, excel_app
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
debug_mode = self.debug_var.get()
|
debug_mode = self.debug_var.get()
|
||||||
@@ -467,13 +454,14 @@ class BatchTableExtractorApp:
|
|||||||
self.root.after(0, lambda: self.log("\n❌ 任务已被用户手动终止!"))
|
self.root.after(0, lambda: self.log("\n❌ 任务已被用户手动终止!"))
|
||||||
break
|
break
|
||||||
|
|
||||||
base_name = os.path.splitext(os.path.basename(file_path))[0]
|
full_name = os.path.basename(file_path)
|
||||||
|
base_name = os.path.splitext(full_name)[0]
|
||||||
target_excel = os.path.join(out_dir, f"{base_name}_表格.xlsx")
|
target_excel = os.path.join(out_dir, f"{base_name}_表格.xlsx")
|
||||||
|
|
||||||
conflict_action = self.conflict_action_var.get()
|
conflict_action = self.conflict_action_var.get()
|
||||||
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=full_name: self.log(f"[{i}/{t}] 跳过同名: {name}"))
|
||||||
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} | 点击终止操作")
|
||||||
@@ -489,7 +477,7 @@ class BatchTableExtractorApp:
|
|||||||
break
|
break
|
||||||
counter += 1
|
counter += 1
|
||||||
|
|
||||||
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=full_name: self.log(f"[{i}/{t}] 处理中: {name}"))
|
||||||
import time
|
import time
|
||||||
t0 = time.time()
|
t0 = time.time()
|
||||||
try:
|
try:
|
||||||
@@ -535,8 +523,7 @@ class BatchTableExtractorApp:
|
|||||||
route_target = "ocr" # fallback
|
route_target = "ocr" # fallback
|
||||||
|
|
||||||
if route_target == "word":
|
if route_target == "word":
|
||||||
ensure_apps()
|
tc = export_single_doc_tables(file_path, target_excel,
|
||||||
tc = export_single_doc_tables(word_app, excel_app, file_path, target_excel,
|
|
||||||
log_func=my_log, debug=debug_mode)
|
log_func=my_log, debug=debug_mode)
|
||||||
else:
|
else:
|
||||||
from core.extractor import export_pdf_image_tables_local
|
from core.extractor import export_pdf_image_tables_local
|
||||||
@@ -554,9 +541,9 @@ class BatchTableExtractorApp:
|
|||||||
import traceback
|
import traceback
|
||||||
trace_str = traceback.format_exc()
|
trace_str = traceback.format_exc()
|
||||||
if self.debug_var.get():
|
if self.debug_var.get():
|
||||||
err_msg = f" ❌ 失败跳过 [{base_name}]: {e}\n{trace_str}"
|
err_msg = f" ❌ 失败跳过 [{full_name}]: {e}\n{trace_str}"
|
||||||
else:
|
else:
|
||||||
err_msg = f" ❌ 失败跳过 [{base_name}]: {e}"
|
err_msg = f" ❌ 失败跳过 [{full_name}]: {e}"
|
||||||
self.root.after(0, lambda m=err_msg: self.log(m, tag="error"))
|
self.root.after(0, lambda m=err_msg: self.log(m, tag="error"))
|
||||||
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}")
|
||||||
|
|
||||||
@@ -572,16 +559,6 @@ class BatchTableExtractorApp:
|
|||||||
self.root.after(0, lambda err=str(e): self.log(f"引擎崩溃: {err}"))
|
self.root.after(0, lambda err=str(e): self.log(f"引擎崩溃: {err}"))
|
||||||
self.root.after(0, lambda err=str(e): messagebox.showerror("错误", f"自动化引擎初始化失败:\n{err}"))
|
self.root.after(0, lambda err=str(e): messagebox.showerror("错误", f"自动化引擎初始化失败:\n{err}"))
|
||||||
finally:
|
finally:
|
||||||
if word_app:
|
|
||||||
try:
|
|
||||||
word_app.DisplayAlerts = True
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
if excel_app:
|
|
||||||
try:
|
|
||||||
excel_app.DisplayAlerts = True
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
def _reset_btn():
|
def _reset_btn():
|
||||||
self.btn_run.config_btn(state=tk.NORMAL, text="开始全量提取表格", command=self._start)
|
self.btn_run.config_btn(state=tk.NORMAL, text="开始全量提取表格", command=self._start)
|
||||||
self.btn_run.set_progress(0.0)
|
self.btn_run.set_progress(0.0)
|
||||||
|
|||||||
Reference in New Issue
Block a user