Files
WordTableExtractor/src/core/extractor.py
T

202 lines
7.3 KiB
Python

import os
import pythoncom
import win32com.client as win32
def detect_and_create_apps():
"""探测并绑定 Microsoft Office 或 WPS 引擎"""
# 1. 探测 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:
pass
# 2. 探测 WPS Office
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:
pass
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
try:
if debug and log_func:
log_func(f" [Debug] 正在调用 COM 接口打开文档: {abs_doc}")
try:
doc = word_app.Documents.Open(FileName=abs_doc, ReadOnly=True, Visible=debug, ConfirmConversions=False)
except Exception as e:
if debug and log_func:
log_func(f" [Debug] 打开失败,疑似遇到受保护的视图拦截,尝试启动智能复制逃逸机制...")
import shutil
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)}")
shutil.copy2(abs_doc, file_to_clean)
doc = word_app.Documents.Open(FileName=file_to_clean, ReadOnly=True, Visible=debug, ConfirmConversions=False)
table_count = doc.Tables.Count
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}"
# 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)
if log_func:
log_func(f" [成功] 提取完成 ({table_count}个表格) -> {os.path.basename(excel_path)}")
return table_count
finally:
if wb:
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):
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):
import subprocess
import os
import sys
# 查找插件路径 (支持直接在 ocr_plugin 下,也支持嵌套在 ocr_worker 下)
plugin_paths = [
os.path.join(os.getcwd(), "ocr_plugin", "ocr_worker.exe"),
os.path.join(os.getcwd(), "ocr_plugin", "ocr_worker", "ocr_worker.exe"),
os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), "ocr_plugin", "ocr_worker.exe"),
os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), "ocr_plugin", "ocr_worker", "ocr_worker.exe")
]
plugin_exe = None
for p in plugin_paths:
if os.path.exists(p):
plugin_exe = p
break
if not plugin_exe:
raise Exception("未检测到本地 AI 插件!请下载 'ocr_plugin' 文件夹并放置在程序同一目录下。")
if log_func:
log_func(f" [AI] 已唤醒本地 AI 引擎,正在全力识别中,请耐心等待...")
abs_excel = os.path.abspath(excel_path)
if os.path.exists(abs_excel):
try:
os.remove(abs_excel)
except:
pass
cmd = [plugin_exe, file_path, abs_excel]
if pages_str:
cmd.extend(["--pages", pages_str])
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
try:
result = subprocess.run(cmd, startupinfo=startupinfo, capture_output=True, text=True, encoding='utf-8', errors='replace')
if result.returncode != 0:
if "No tables detected" in result.stdout:
if log_func:
log_func(f" [跳过] 未检测到任何表格。")
return 0
raise Exception(f"AI 引擎运行失败: {result.stderr or result.stdout}")
if "No tables detected" in result.stdout:
if log_func:
log_func(f" [跳过] 未检测到任何表格。")
return 0
import re
m = re.search(r"Successfully extracted (\d+) tables", result.stdout)
table_count = int(m.group(1)) if m else 1
if log_func:
log_func(f" [成功] 提取完成 ({table_count}个表格) -> {os.path.basename(excel_path)}")
return table_count
except Exception as e:
raise Exception(f"调用本地 AI 失败: {e}")