Refactor: Replace Office COM extraction with python-docx and add WPS fallback for doc conversion

This commit is contained in:
HONOR
2026-09-20 10:33:15 +08:00
parent 8dcd7c4031
commit 49c04a231a
3 changed files with 122 additions and 180 deletions
+3
View File
@@ -1,2 +1,5 @@
pywin32
windnd
python-docx
openpyxl
pandas
+116 -124
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():
try:
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)
pythoncom.CoInitialize()
word_app = None
doc = None
wb = None
file_to_clean = None
try:
if debug and log_func:
log_func(f" [Debug] 正在调用 COM 接口打开文档: {abs_doc}")
log_func(f" [Debug] 正在启动独立 Word 进程转换 .doc 文件...")
# 优先尝试启动全新独立的 MS Word 进程
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
word_app = win32.DispatchEx('Word.Application')
except Exception:
# 如果没有 MS Word,尝试启动 WPS
try:
word_app = win32.DispatchEx('wps.Application')
except Exception:
try:
word_app = win32.DispatchEx('kwps.Application')
except Exception:
# 如果当前 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:
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 log_func:
log_func(f" [跳过] 未检测到表格: {os.path.basename(doc_path)}")
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))
else:
ws = wb.Sheets.Item(i)
ws.Name = f"Table_{i}"
wb = Workbook()
wb.remove(wb.active) # 移除默认的Sheet
for i, table in enumerate(tables):
sheet_name = f"Table_{i+1}"
ws = wb.create_sheet(title=sheet_name)
# 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() # 最后一次尝试,若失败则抛出异常
# 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)
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):
+3 -56
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:
@@ -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.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")
@@ -414,43 +407,8 @@ 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()
@@ -535,8 +493,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
@@ -572,16 +529,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)