Files
WordTableExtractor/src/core/extractor.py
T

131 lines
4.4 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)
except Exception as e:
if debug and log_func:
log_func(f" [Debug] 打开失败,疑似遇到受保护的视图拦截,尝试启动智能复制逃逸机制...")
import shutil
out_dir = os.path.dirname(abs_excel)
file_to_clean = os.path.join(out_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)
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)
except Exception:
pass