4 changed files with 186 additions and 199 deletions
+15
View File
@@ -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 交互规范
- 点击“开始提取”或拖拽文件时,必须第一时间清空日志窗口,确保运行日志清爽。
+3
View File
@@ -1,2 +1,5 @@
pywin32
windnd
python-docx
openpyxl
pandas
+101 -109
View File
@@ -2,157 +2,149 @@ import os
import pythoncom
import win32com.client as win32
def detect_and_create_apps(engine_choice="自动判断 (推荐)"):
"""探测并绑定 Microsoft Office 或 WPS 引擎"""
def convert_doc_to_docx(doc_path, log_func=None, debug=False):
"""
静默将 .doc 转换为 .docx,不影响用户已打开的任何 Word 文档。
使用独立进程 (DispatchEx) 和只读模式 (ReadOnly=True)。
"""
import tempfile
import pythoncom
def try_ms_office():
pythoncom.CoInitialize()
word_app = None
doc = None
try:
word = win32.gencache.EnsureDispatch('Word.Application')
excel = win32.gencache.EnsureDispatch('Excel.Application')
return word, excel, "Microsoft Office"
if debug and log_func:
log_func(f" [Debug] 正在启动独立 Word 进程转换 .doc 文件...")
# 优先尝试启动全新独立的 MS Word 进程
try:
word_app = win32.DispatchEx('Word.Application')
except Exception:
# 如果没有 MS Word,尝试启动 WPS
try:
word_app = win32.DispatchEx('wps.Application')
except Exception:
try:
word = win32.Dispatch('Word.Application')
excel = win32.Dispatch('Excel.Application')
return word, excel, "Microsoft Office"
word_app = win32.DispatchEx('kwps.Application')
except Exception:
return None
def try_wps():
# 如果当前 WPS 版本不支持 DispatchEx (独立进程),则降级使用普通 Dispatch
try:
word_app = win32.Dispatch('wps.Application')
except Exception:
word_app = win32.Dispatch('kwps.Application')
word_app.Visible = False
word_app.DisplayAlerts = False
abs_doc = os.path.abspath(doc_path)
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:
word = win32.gencache.EnsureDispatch('wps.Application')
os.remove(temp_docx)
except Exception:
word = win32.Dispatch('kwps.Application')
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:
excel = win32.gencache.EnsureDispatch('et.Application')
doc.Close(SaveChanges=False)
except Exception:
excel = win32.Dispatch('ket.Application')
return word, excel, "WPS Office"
pass
if word_app:
try:
word_app.Quit()
except Exception:
return None
pass
pythoncom.CoUninitialize()
if engine_choice == "Microsoft Office":
res = try_ms_office()
if res: return res
raise RuntimeError("未检测到可用的 Microsoft Office!请尝试选择 WPS Office 或 自动判断。")
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
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
wb = None
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] 正在调用 COM 接口打开文档: {abs_doc}")
log_func(f" [Debug] 正在使用 python-docx 解析文档...")
try:
doc = word_app.Documents.Open(abs_doc)
# 尝试访问属性,如果在“受保护的视图”下,这行会抛出 0x80020009 异常
table_count = doc.Tables.Count
except Exception as e:
if debug and log_func:
log_func(f" [Debug] 访问受阻(可能是受保护的视图),启动智能复制逃逸机制...")
out_dir = os.path.dirname(abs_excel)
temp_dir = os.path.join(out_dir, "temp")
if not os.path.exists(temp_dir):
os.makedirs(temp_dir, exist_ok=True)
file_to_clean = os.path.join(temp_dir, f"~temp_bypass_{os.path.basename(abs_doc)}")
# 使用原生读写剥离 Windows 的 Zone.Identifier (MOTW) 流
with open(abs_doc, 'rb') as f_in:
with open(file_to_clean, 'wb') as f_out:
f_out.write(f_in.read())
doc = word_app.Documents.Open(file_to_clean)
table_count = doc.Tables.Count
doc = Document(abs_doc)
tables = doc.tables
table_count = len(tables)
if table_count == 0:
if log_func:
log_func(f" [跳过] 未检测到表格: {os.path.basename(doc_path)}")
return 0
wb = excel_app.Workbooks.Add()
wb = Workbook()
wb.remove(wb.active) # 移除默认的Sheet
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()
for i, table in enumerate(tables):
sheet_name = f"Table_{i+1}"
ws = wb.create_sheet(title=sheet_name)
import time
time.sleep(0.2) # 给系统剪贴板同步数据留点时间
# python-docx 提取表格数据 (简单遍历,处理了基本的合并单元格结构)
for r_idx, row in enumerate(table.rows):
row_data = []
for cell in row.cells:
row_data.append(cell.text.strip())
ws.append(row_data)
if i > wb.Sheets.Count:
ws = wb.Sheets.Add(After=wb.Sheets(wb.Sheets.Count))
else:
ws = wb.Sheets.Item(i)
ws.Name = f"Table_{i}"
# 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()
# 51 = xlOpenXMLWorkbook (.xlsx)
# 如果存在旧文件先删除
if os.path.exists(abs_excel):
try:
os.remove(abs_excel)
except Exception:
pass
wb.SaveAs(Filename=abs_excel, FileFormat=51)
wb.save(abs_excel)
if log_func:
log_func(f" [成功] 提取完成 ({table_count}个表格) -> {os.path.basename(excel_path)}")
return table_count
except Exception as e:
if log_func:
log_func(f" [Error] 提取失败: {e}")
raise
finally:
if wb:
try:
wb.Close(SaveChanges=False)
except Exception:
pass
if doc:
try:
doc.Close(SaveChanges=False)
except Exception:
pass
# 清理 .doc 转换产生的临时文件
if file_to_clean and os.path.exists(file_to_clean):
try:
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:
pass
def export_pdf_image_tables_local(excel_app, file_path, excel_path, pages_str, log_func=None, debug=False):
+52 -75
View File
@@ -10,7 +10,7 @@ import datetime
import time
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.history_window import record_log
@@ -44,7 +44,6 @@ class BatchTableExtractorApp:
self.conflict_action_var = tk.StringVar(value="直接覆盖 (默认)")
self.pdf_engine_var = tk.StringVar(value="不处理")
self.engine_var = tk.StringVar(value="自动判断 (推荐)")
import threading
self._stop_event = threading.Event()
@@ -95,8 +94,7 @@ class BatchTableExtractorApp:
"debug_mode": self.debug_var.get(),
"topmost": self.topmost_var.get(),
"conflict_action": self.conflict_action_var.get(),
"pdf_engine": self.pdf_engine_var.get(),
"engine_var": self.engine_var.get()
"pdf_engine": self.pdf_engine_var.get()
}
try:
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
@@ -139,25 +137,24 @@ class BatchTableExtractorApp:
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)
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. 路径配置
path_box = ttk.LabelFrame(frame, text=" 路径设置 ", padding="10")
path_box.pack(fill=tk.X, pady=(0, 10))
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 = 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.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=50)
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.Entry(path_box, textvariable=self.out_dir_var, width=46, 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.grid(row=1, column=2, sticky=tk.EW)
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=50)
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)
@@ -171,14 +168,8 @@ class BatchTableExtractorApp:
cb_conflict.pack(side=tk.LEFT, fill=tk.X, expand=True)
cb_conflict.bind("<<ComboboxSelected>>", _clear_combo_focus)
ttk.Label(combo_frame, text=" PDF: ").pack(side=tk.LEFT)
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)
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)
path_box.columnconfigure(1, weight=1)
@@ -247,6 +238,34 @@ class BatchTableExtractorApp:
if 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):
if not files:
return
@@ -335,6 +354,9 @@ class BatchTableExtractorApp:
def _start(self):
self._save_config()
# 点击提取按钮时,第一时间清空上一次的运行日志
self.txt.delete(1.0, tk.END)
src = self.src_path_var.get().strip()
out = self.out_dir_var.get().strip()
mode = self.mode_var.get()
@@ -414,44 +436,9 @@ class BatchTableExtractorApp:
return f"{date_str}X{seq:02d}"
def _worker(self, file_list, out_dir):
pythoncom.CoInitialize()
word_app = None
excel_app = None
apps_initialized = False
success_count = 0
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:
debug_mode = self.debug_var.get()
@@ -467,13 +454,14 @@ class BatchTableExtractorApp:
self.root.after(0, lambda: self.log("\n❌ 任务已被用户手动终止!"))
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")
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.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, "发现同名文件,跳过")
def update_skip_btn(i=idx, t=total):
self.btn_run.config_btn(text=f"提取中 {i}/{t} | 点击终止操作")
@@ -489,7 +477,7 @@ class BatchTableExtractorApp:
break
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
t0 = time.time()
try:
@@ -535,8 +523,7 @@ class BatchTableExtractorApp:
route_target = "ocr" # fallback
if route_target == "word":
ensure_apps()
tc = export_single_doc_tables(word_app, excel_app, file_path, target_excel,
tc = export_single_doc_tables(file_path, target_excel,
log_func=my_log, debug=debug_mode)
else:
from core.extractor import export_pdf_image_tables_local
@@ -554,9 +541,9 @@ class BatchTableExtractorApp:
import traceback
trace_str = traceback.format_exc()
if self.debug_var.get():
err_msg = f" ❌ 失败跳过 [{base_name}]: {e}\n{trace_str}"
err_msg = f" ❌ 失败跳过 [{full_name}]: {e}\n{trace_str}"
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"))
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): messagebox.showerror("错误", f"自动化引擎初始化失败:\n{err}"))
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():
self.btn_run.config_btn(state=tk.NORMAL, text="开始全量提取表格", command=self._start)
self.btn_run.set_progress(0.0)