Compare commits
29
Commits
9dbf73ae7e
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8dcd7c4031 | ||
|
|
c07f958d40 | ||
|
|
2dcd40cf6e | ||
|
|
8f87562feb | ||
|
|
edb390e4f8 | ||
|
|
926a5b7dd1 | ||
|
|
f1b1d4e453 | ||
|
|
d17c52403d | ||
|
|
ebfc197c31 | ||
|
|
c59153253c | ||
|
|
944d2f7888 | ||
|
|
dbab45baaf | ||
|
|
2e7a22c207 | ||
|
|
bd2365f2dd | ||
|
|
fec5ceed33 | ||
|
|
1fce2a6271 | ||
|
|
6a0040580e | ||
|
|
a350054271 | ||
|
|
2dda08aa98 | ||
|
|
ad162ef7d7 | ||
|
|
2ee9a38da0 | ||
|
|
7eed21f33f | ||
|
|
02ec382d88 | ||
|
|
15f7b0ea2b | ||
|
|
a94b539d9e | ||
|
|
77ed83cc55 | ||
|
|
147b8932be | ||
|
|
d41de616d7 | ||
|
|
261b20bf82 |
@@ -0,0 +1,8 @@
|
|||||||
|
**/__pycache__
|
||||||
|
config.json
|
||||||
|
conversion.csv
|
||||||
|
/build
|
||||||
|
/dist
|
||||||
|
/WordTableExtractor.spec
|
||||||
|
ocr_worker.spec
|
||||||
|
/scratch
|
||||||
@@ -6,32 +6,41 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 核心特性
|
## 🌟 核心特性
|
||||||
|
|
||||||
* **合并单元格无损迁移**:直接映射底层表格拓扑结构,彻底避免跨行跨列时出现的列整体左移、错位问题。
|
* **合并单元格无损迁移**:直接映射底层表格拓扑结构,彻底避免跨行跨列时出现的列整体左移、错位问题。
|
||||||
* **全量提取(无截断限制)**:针对 100+ 行超长清单设计,完整保留文档中的所有行与列。
|
* **全新扁平化 UI 设计**:界面全面升级为无边框扁平化风格。独创悬浮式绿色流体进度条按钮,状态与进度直观融合。
|
||||||
* **智能自适应引擎**:自动探测宿主环境。优先调用 **Microsoft Office**,若未安装则自动平滑降级调用 **WPS Office**,免除环境配置烦恼。
|
* **智能自适应引擎**:自动探测宿主环境。优先调用 **Microsoft Office**,若未安装则自动平滑降级调用 **WPS Office**,免除环境配置烦恼。
|
||||||
* **双模式处理**:支持单独处理单份文件,或递归扫描整个文件夹及其子目录进行批量转换。
|
* **灵活的多文件处理**:支持拖拽文件/文件夹快速提取。支持单独处理单份文件,或递归扫描整个文件夹及其子目录进行批量转换。
|
||||||
* **配置自动持久化**:记住上次选择的导出路径、来源目录及递归选项,写入本地 `config.json`(支持开发与 `.exe` 打包环境自动适配路径)。
|
* **安全的中断与控制**:支持提取过程中途暂停,弹出确认保护防止误触关闭;遇到同名文件可灵活选择直接覆盖、自动重命名或跳过。
|
||||||
|
* **详尽的历史日志追踪**:内置本地 CSV 转换日志,通过一键“日志”面板随时追溯每次批处理的成功数、耗时、表格数及报错详情。
|
||||||
* **独立单文件(免环境)**:可打包为纯净单文件可执行程序,目标机器无需配置 Python 或 Java 环境,开箱即用。
|
* **独立单文件(免环境)**:可打包为纯净单文件可执行程序,目标机器无需配置 Python 或 Java 环境,开箱即用。
|
||||||
|
* **PDF 与扫描件图片支持**:内置百度智能云 OCR 引擎接口,支持将 PDF(含扫描件)和图片文件发送至云端高精度提取表格,无缝汇总为 Excel。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 项目结构
|
## 📁 项目结构
|
||||||
|
|
||||||
```text
|
```text
|
||||||
WordTableExtractor/
|
WordTableExtractor/
|
||||||
├── src/
|
├── src/
|
||||||
│ └── smart_batch_table_extractor_gui.py # 主程序核心源码
|
│ ├── core/
|
||||||
├── config.json # 用户配置(运行后自动生成在根目录)
|
│ │ └── extractor.py # Office/WPS 自动化引擎交互核心
|
||||||
|
│ ├── ui/
|
||||||
|
│ │ ├── gui.py # 扁平化 UI 界面及主线程业务逻辑
|
||||||
|
│ │ ├── history_window.py # 历史日志过滤与详情弹窗
|
||||||
|
│ │ └── widgets.py # 定制化 UI 组件 (如 ProgressButton)
|
||||||
|
│ ├── utils/
|
||||||
|
│ │ └── config.py # 环境配置、通用路径解析
|
||||||
|
│ └── main.py # 应用程序启动入口
|
||||||
|
├── .gitignore
|
||||||
├── LICENSE
|
├── LICENSE
|
||||||
└── README.md
|
└── README.md
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 快速上手(源码运行)
|
## 🚀 快速上手(源码运行)
|
||||||
|
|
||||||
### 1. 环境要求
|
### 1. 环境要求
|
||||||
|
|
||||||
@@ -42,8 +51,7 @@ WordTableExtractor/
|
|||||||
### 2. 安装依赖
|
### 2. 安装依赖
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
pip install pywin32
|
pip install pywin32 windnd requests pymupdf
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
> **Windows 下安装 `pywin32` 后的初始化提示**:
|
> **Windows 下安装 `pywin32` 后的初始化提示**:
|
||||||
@@ -52,21 +60,25 @@ pip install pywin32
|
|||||||
> python -c "import sys, os; print(os.path.join(sys.prefix, 'Scripts', 'pywin32_postinstall.py'))"
|
> python -c "import sys, os; print(os.path.join(sys.prefix, 'Scripts', 'pywin32_postinstall.py'))"
|
||||||
> # 执行打印出的完整脚本路径:
|
> # 执行打印出的完整脚本路径:
|
||||||
> python <完整路径> -install
|
> python <完整路径> -install
|
||||||
>
|
|
||||||
> ```
|
> ```
|
||||||
>
|
|
||||||
>
|
|
||||||
|
|
||||||
### 3. 运行程序
|
### 3. 配置百度 OCR 接口(仅在需要提取 PDF/图片 时需要)
|
||||||
|
|
||||||
|
为了提取 PDF 扫描件和图片,你需要前往 **[百度智能云控制台](https://console.bce.baidu.com/ai/#/ai/ocr/overview/index)** 免费申请表格识别的 API 密钥:
|
||||||
|
1. 注册并实名认证百度智能云账号。
|
||||||
|
2. 找到“人工智能” -> “文字识别”,点击“创建应用”。
|
||||||
|
3. 勾选需要包含的接口(确保勾选“表格文字识别”),创建完毕后即可获得 **API Key (AK)** 和 **Secret Key (SK)**。
|
||||||
|
4. 打开本工具主界面,点击 **⚙️ OCR API** 设置,将 AK 和 SK 填入并保存。
|
||||||
|
|
||||||
|
### 4. 运行程序
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python smart_batch_table_extractor_gui.py
|
python src/main.py
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 打包为独立 EXE(免安装环境分发)
|
## 📦 打包为独立 EXE(免安装环境分发)
|
||||||
|
|
||||||
若需要分发给没有 Python 环境的同事或部署在业务现场机器,可使用 PyInstaller 编译为单文件绿色版程序。
|
若需要分发给没有 Python 环境的同事或部署在业务现场机器,可使用 PyInstaller 编译为单文件绿色版程序。
|
||||||
|
|
||||||
@@ -74,38 +86,24 @@ python smart_batch_table_extractor_gui.py
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
pip install pyinstaller
|
pip install pyinstaller
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. 执行编译命令(优化瘦身体积)
|
### 2. 执行编译命令(优化瘦身体积)
|
||||||
|
|
||||||
执行以下指令,排除不必要的测试套件与调试模块:
|
在项目根目录下执行以下指令,排除不必要的调试模块:
|
||||||
|
|
||||||
```
|
```bash
|
||||||
pyinstaller -F -w `
|
python -m PyInstaller -y -F -w --icon="app.ico" --add-data "app.ico;." --hidden-import "win32com.client" --hidden-import "pythoncom" --hidden-import "pywintypes" --hidden-import "requests" --hidden-import "fitz" --exclude-module "win32com.test" --exclude-module "win32com.demos" --exclude-module "win32com.axdebug" --exclude-module "win32com.axscript" --exclude-module "win32com.directsound" --exclude-module "win32com.mapi" --exclude-module "setuptools" --exclude-module "distutils" --name "WordTableExtractor" src/main.py
|
||||||
--hidden-import "win32com.client" `
|
|
||||||
--hidden-import "pythoncom" `
|
|
||||||
--hidden-import "pywintypes" `
|
|
||||||
--exclude-module "win32com.test" `
|
|
||||||
--exclude-module "win32com.demos" `
|
|
||||||
--exclude-module "win32com.axdebug" `
|
|
||||||
--exclude-module "win32com.axscript" `
|
|
||||||
--exclude-module "win32com.directsound" `
|
|
||||||
--exclude-module "win32com.mapi" `
|
|
||||||
--exclude-module "setuptools" `
|
|
||||||
--exclude-module "distutils" `
|
|
||||||
--name "WordTableExtractor" `
|
|
||||||
src/smart_batch_table_extractor_gui.py
|
|
||||||
```
|
```
|
||||||
|
|
||||||
编译完成后,可在 `dist/` 目录下获取 `WordTableExtractor.exe`,直接拷贝至其他 Windows 电脑运行。
|
编译完成后,可在 `dist/` 目录下获取 `WordTableExtractor.exe`,直接拷贝至其他 Windows 电脑运行。配置信息与运行日志将自动在该 exe 所在的目录中生成 `config.json` 与 `conversion.csv`。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 使用说明
|
## 💡 使用说明
|
||||||
|
|
||||||
1. 启动工具后,日志窗口会自动打印当前检测到的办公组件引擎(`Microsoft Office` 或 `WPS Office`)。
|
1. **引擎初始化**:启动工具后,日志窗口会自动打印当前检测到的办公组件引擎(优先 `Microsoft Office`,兜底 `WPS Office`)。
|
||||||
2. 根据需求选择 **“批量处理文件夹”** 或 **“处理单个文件”**。
|
2. **选择模式**:根据需求选择 **“批量处理文件夹”** 或 **“处理单个文件”**,也可直接将文档或文件夹**拖拽**到主窗口中。
|
||||||
3. 指定来源路径与导出目标目录。
|
3. **同名策略**:当导出目标目录中已存在同名生成的 Excel 时,可在界面左侧调整策略(直接覆盖、自动重命名、直接跳过)。
|
||||||
4. 点击 **“开始全量提取表格”**,进度条与日志窗口将实时展示每个文件的提取结果与表格数量。
|
4. **进度与中途终止**:点击 **“开始全量提取表格”**,流体进度条将接管整个按钮。提取过程中若需停止,只需点击进度条或直接关闭窗口,均会触发友好的中断确认保护机制。
|
||||||
5. 转换生成的目标文件命名格式统一为:`{原文件名}_表格.xlsx`。
|
5. **溯源与日志**:点击右侧的 **“日志”** 按钮即可弹出过滤搜索面板,查看所有历史批次的提取详情。若某文件提取失败,可双击该行日志查看报错栈追溯原因。
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
pywin32
|
||||||
|
windnd
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
import os
|
||||||
|
import pythoncom
|
||||||
|
import win32com.client as win32
|
||||||
|
|
||||||
|
def detect_and_create_apps(engine_choice="自动判断 (推荐)"):
|
||||||
|
"""探测并绑定 Microsoft Office 或 WPS 引擎"""
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
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(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
|
||||||
|
|
||||||
|
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}")
|
||||||
+3
-338
@@ -1,342 +1,7 @@
|
|||||||
import os
|
|
||||||
import sys
|
|
||||||
import json
|
|
||||||
import glob
|
|
||||||
import threading
|
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from tkinter import filedialog, messagebox, ttk
|
# 确保最先导入 config 以完成环境配置(尤其是 pywin32 的 dll 问题)
|
||||||
|
import utils.config
|
||||||
# 兼容 Python 3.13 动态加载系统目录
|
from ui.gui import BatchTableExtractorApp
|
||||||
pywin32_dir = os.path.join(sys.prefix, "Lib", "site-packages", "pywin32_system32")
|
|
||||||
if os.path.exists(pywin32_dir):
|
|
||||||
try:
|
|
||||||
os.add_dll_directory(pywin32_dir)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
import pythoncom
|
|
||||||
import win32com.client as win32
|
|
||||||
|
|
||||||
# ---------------- 获取运行与配置目录 ----------------
|
|
||||||
if getattr(sys, 'frozen', False):
|
|
||||||
# 打包为 exe 后:与 exe 同级
|
|
||||||
APP_DIR = os.path.dirname(sys.executable)
|
|
||||||
else:
|
|
||||||
# 源码开发调试:定位到 src 的上一层(项目根目录)
|
|
||||||
APP_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
||||||
|
|
||||||
CONFIG_FILE = os.path.join(APP_DIR, "config.json")
|
|
||||||
|
|
||||||
|
|
||||||
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):
|
|
||||||
"""提取单个 Word 文件中的所有表格到 Excel"""
|
|
||||||
abs_doc = os.path.abspath(doc_path)
|
|
||||||
abs_excel = os.path.abspath(excel_path)
|
|
||||||
|
|
||||||
doc = None
|
|
||||||
wb = None
|
|
||||||
try:
|
|
||||||
doc = word_app.Documents.Open(abs_doc, ReadOnly=True)
|
|
||||||
table_count = doc.Tables.Count
|
|
||||||
|
|
||||||
if table_count == 0:
|
|
||||||
if log_func:
|
|
||||||
log_func(f" [跳过] 未检测到表格: {os.path.basename(doc_path)}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
wb = excel_app.Workbooks.Add()
|
|
||||||
|
|
||||||
for i in range(1, table_count + 1):
|
|
||||||
table = doc.Tables.Item(i)
|
|
||||||
table.Range.Copy()
|
|
||||||
|
|
||||||
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}"
|
|
||||||
ws.Paste()
|
|
||||||
ws.Columns.AutoFit()
|
|
||||||
|
|
||||||
while wb.Sheets.Count > table_count:
|
|
||||||
wb.Sheets(wb.Sheets.Count).Delete()
|
|
||||||
|
|
||||||
wb.SaveAs(abs_excel)
|
|
||||||
if log_func:
|
|
||||||
log_func(f" [成功] 提取完成 ({table_count}个表格) -> {os.path.basename(excel_path)}")
|
|
||||||
return True
|
|
||||||
finally:
|
|
||||||
if wb:
|
|
||||||
try:
|
|
||||||
wb.Close(SaveChanges=True)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
if doc:
|
|
||||||
try:
|
|
||||||
doc.Close(SaveChanges=False)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class BatchTableExtractorApp:
|
|
||||||
def __init__(self, root):
|
|
||||||
self.root = root
|
|
||||||
self.root.title("Word 表格全量批量导出工具 (Office/WPS 通用版)")
|
|
||||||
self.root.geometry("640x520")
|
|
||||||
self.root.minsize(580, 460)
|
|
||||||
|
|
||||||
# 状态变量
|
|
||||||
self.mode_var = tk.StringVar(value="dir") # "file" 或 "dir"
|
|
||||||
self.src_path_var = tk.StringVar()
|
|
||||||
self.out_dir_var = tk.StringVar()
|
|
||||||
self.recursive_var = tk.BooleanVar(value=False)
|
|
||||||
|
|
||||||
self._load_config()
|
|
||||||
self._build_ui()
|
|
||||||
self._on_mode_change()
|
|
||||||
|
|
||||||
# 窗口关闭时自动持久化配置
|
|
||||||
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
|
|
||||||
|
|
||||||
def _load_config(self):
|
|
||||||
"""读取本地配置文件"""
|
|
||||||
if os.path.exists(CONFIG_FILE):
|
|
||||||
try:
|
|
||||||
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
|
|
||||||
cfg = json.load(f)
|
|
||||||
self.mode_var.set(cfg.get("mode", "dir"))
|
|
||||||
self.src_path_var.set(cfg.get("src_path", ""))
|
|
||||||
self.out_dir_var.set(cfg.get("out_dir", ""))
|
|
||||||
self.recursive_var.set(cfg.get("recursive", False))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def _save_config(self):
|
|
||||||
"""写入配置到本地 JSON"""
|
|
||||||
cfg = {
|
|
||||||
"mode": self.mode_var.get(),
|
|
||||||
"src_path": self.src_path_var.get(),
|
|
||||||
"out_dir": self.out_dir_var.get(),
|
|
||||||
"recursive": self.recursive_var.get()
|
|
||||||
}
|
|
||||||
try:
|
|
||||||
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
|
||||||
json.dump(cfg, f, ensure_ascii=False, indent=2)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def _build_ui(self):
|
|
||||||
frame = ttk.Frame(self.root, padding="15")
|
|
||||||
frame.pack(fill=tk.BOTH, expand=True)
|
|
||||||
|
|
||||||
# 1. 模式选择
|
|
||||||
mode_box = ttk.LabelFrame(frame, text=" 处理模式 ", padding="8")
|
|
||||||
mode_box.pack(fill=tk.X, pady=(0, 10))
|
|
||||||
|
|
||||||
ttk.Radiobutton(mode_box, text="批量处理文件夹", variable=self.mode_var, value="dir",
|
|
||||||
command=self._on_mode_change).pack(side=tk.LEFT, padx=15)
|
|
||||||
ttk.Radiobutton(mode_box, text="处理单个文件", variable=self.mode_var, value="file",
|
|
||||||
command=self._on_mode_change).pack(side=tk.LEFT, padx=15)
|
|
||||||
self.chk_recursive = ttk.Checkbutton(mode_box, text="包含子文件夹", variable=self.recursive_var)
|
|
||||||
self.chk_recursive.pack(side=tk.RIGHT, padx=10)
|
|
||||||
|
|
||||||
# 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 = ttk.Button(path_box, text="选择...", command=self._browse_src)
|
|
||||||
self.btn_browse_src.grid(row=0, column=2)
|
|
||||||
|
|
||||||
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).grid(row=1, column=1, sticky=tk.EW, padx=6)
|
|
||||||
ttk.Button(path_box, text="选择...", command=self._browse_out).grid(row=1, column=2)
|
|
||||||
|
|
||||||
path_box.columnconfigure(1, weight=1)
|
|
||||||
|
|
||||||
# 3. 运行操作区
|
|
||||||
self.btn_run = ttk.Button(frame, text="开始全量提取表格", command=self._start)
|
|
||||||
self.btn_run.pack(fill=tk.X, ipady=5, pady=(0, 8))
|
|
||||||
|
|
||||||
self.bar = ttk.Progressbar(frame, mode='determinate')
|
|
||||||
self.bar.pack(fill=tk.X, pady=(0, 10))
|
|
||||||
|
|
||||||
# 4. 运行日志窗口
|
|
||||||
log_box = ttk.LabelFrame(frame, text=" 运行日志 ", padding="8")
|
|
||||||
log_box.pack(fill=tk.BOTH, expand=True)
|
|
||||||
|
|
||||||
self.txt = tk.Text(log_box, wrap=tk.WORD, height=8, font=("Consolas", 9))
|
|
||||||
self.txt.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
|
|
||||||
sb = ttk.Scrollbar(log_box, orient=tk.VERTICAL, command=self.txt.yview)
|
|
||||||
sb.pack(side=tk.RIGHT, fill=tk.Y)
|
|
||||||
self.txt.config(yscrollcommand=sb.set)
|
|
||||||
|
|
||||||
def _on_mode_change(self):
|
|
||||||
if self.mode_var.get() == "dir":
|
|
||||||
self.lbl_src.config(text="来源目录:")
|
|
||||||
self.chk_recursive.config(state=tk.NORMAL)
|
|
||||||
else:
|
|
||||||
self.lbl_src.config(text="来源文件:")
|
|
||||||
self.chk_recursive.config(state=tk.DISABLED)
|
|
||||||
|
|
||||||
def _browse_src(self):
|
|
||||||
if self.mode_var.get() == "dir":
|
|
||||||
path = filedialog.askdirectory(title="选择包含 Word 文件的目录")
|
|
||||||
else:
|
|
||||||
path = filedialog.askopenfilename(
|
|
||||||
title="选择 Word 文档",
|
|
||||||
filetypes=[("Word 文档", "*.doc *.docx"), ("所有文件", "*.*")]
|
|
||||||
)
|
|
||||||
if path:
|
|
||||||
self.src_path_var.set(path)
|
|
||||||
if not self.out_dir_var.get():
|
|
||||||
self.out_dir_var.set(path if self.mode_var.get() == "dir" else os.path.dirname(path))
|
|
||||||
|
|
||||||
def _browse_out(self):
|
|
||||||
path = filedialog.askdirectory(title="选择输出目录")
|
|
||||||
if path:
|
|
||||||
self.out_dir_var.set(path)
|
|
||||||
|
|
||||||
def log(self, msg):
|
|
||||||
self.txt.insert(tk.END, f"{msg}\n")
|
|
||||||
self.txt.see(tk.END)
|
|
||||||
|
|
||||||
def _on_close(self):
|
|
||||||
self._save_config()
|
|
||||||
self.root.destroy()
|
|
||||||
|
|
||||||
def _start(self):
|
|
||||||
self._save_config()
|
|
||||||
src = self.src_path_var.get().strip()
|
|
||||||
out = self.out_dir_var.get().strip()
|
|
||||||
mode = self.mode_var.get()
|
|
||||||
recursive = self.recursive_var.get()
|
|
||||||
|
|
||||||
if not src or not os.path.exists(src):
|
|
||||||
messagebox.showwarning("提示", "请选择有效的来源文件或目录!")
|
|
||||||
return
|
|
||||||
|
|
||||||
if not out or not os.path.isdir(out):
|
|
||||||
messagebox.showwarning("提示", "请选择有效的输出目录!")
|
|
||||||
return
|
|
||||||
|
|
||||||
# 收集目标文件列表
|
|
||||||
files_to_process = []
|
|
||||||
if mode == "file":
|
|
||||||
if src.lower().endswith(('.doc', '.docx')):
|
|
||||||
files_to_process.append(src)
|
|
||||||
else:
|
|
||||||
pattern = "**/*" if recursive else "*"
|
|
||||||
for ext in ("*.doc", "*.docx"):
|
|
||||||
full_pattern = os.path.join(src, pattern, ext) if recursive else os.path.join(src, ext)
|
|
||||||
files_to_process.extend(glob.glob(full_pattern, recursive=recursive))
|
|
||||||
|
|
||||||
# 排除 office 生成的临时文件 (~$开头)
|
|
||||||
files_to_process = [f for f in files_to_process if not os.path.basename(f).startswith("~$")]
|
|
||||||
|
|
||||||
if not files_to_process:
|
|
||||||
messagebox.showinfo("提示", "未找到任何待处理的 .doc 或 .docx 文件!")
|
|
||||||
return
|
|
||||||
|
|
||||||
self.btn_run.config(state=tk.DISABLED)
|
|
||||||
self.bar['value'] = 0
|
|
||||||
self.bar['maximum'] = len(files_to_process)
|
|
||||||
self.log(f"\n===== 开始任务: 共扫描到 {len(files_to_process)} 个文件 =====")
|
|
||||||
|
|
||||||
threading.Thread(
|
|
||||||
target=self._worker,
|
|
||||||
args=(files_to_process, out),
|
|
||||||
daemon=True
|
|
||||||
).start()
|
|
||||||
|
|
||||||
def _worker(self, file_list, out_dir):
|
|
||||||
pythoncom.CoInitialize()
|
|
||||||
word_app = None
|
|
||||||
excel_app = None
|
|
||||||
success_count = 0
|
|
||||||
|
|
||||||
try:
|
|
||||||
word_app, excel_app, engine_name = detect_and_create_apps()
|
|
||||||
self.root.after(0, lambda: self.log(f"已启动宿主引擎: 【{engine_name}】"))
|
|
||||||
|
|
||||||
word_app.Visible = False
|
|
||||||
word_app.DisplayAlerts = False
|
|
||||||
excel_app.Visible = False
|
|
||||||
excel_app.DisplayAlerts = False
|
|
||||||
|
|
||||||
total = len(file_list)
|
|
||||||
for idx, file_path in enumerate(file_list, start=1):
|
|
||||||
base_name = os.path.splitext(os.path.basename(file_path))[0]
|
|
||||||
target_excel = os.path.join(out_dir, f"{base_name}_表格.xlsx")
|
|
||||||
|
|
||||||
self.root.after(0, lambda i=idx, t=total, name=base_name: self.log(f"[{i}/{t}] 处理中: {name}"))
|
|
||||||
try:
|
|
||||||
if export_single_doc_tables(word_app, excel_app, file_path, target_excel,
|
|
||||||
log_func=lambda m: self.root.after(0, self.log, m)):
|
|
||||||
success_count += 1
|
|
||||||
except Exception as e:
|
|
||||||
self.root.after(0, lambda n=base_name, err=str(e): self.log(f" ❌ 出错跳过 [{n}]: {err}"))
|
|
||||||
|
|
||||||
# 更新进度条
|
|
||||||
self.root.after(0, lambda val=idx: self.bar.configure(value=val))
|
|
||||||
|
|
||||||
self.root.after(0, lambda: self.log(f"===== 处理完成!成功导出 {success_count}/{total} 个文档的表格 ====="))
|
|
||||||
self.root.after(0, lambda: messagebox.showinfo("批量完成", f"处理完成!\n成功提取: {success_count}/{total} 个文件。"))
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
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.Quit()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
if excel_app:
|
|
||||||
try:
|
|
||||||
excel_app.Quit()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
pythoncom.CoUninitialize()
|
|
||||||
self.root.after(0, lambda: self.btn_run.config(state=tk.NORMAL))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
app_root = tk.Tk()
|
app_root = tk.Tk()
|
||||||
|
|||||||
+589
@@ -0,0 +1,589 @@
|
|||||||
|
import os
|
||||||
|
import json
|
||||||
|
import glob
|
||||||
|
import threading
|
||||||
|
import tkinter as tk
|
||||||
|
from tkinter import filedialog, messagebox, ttk
|
||||||
|
import pythoncom
|
||||||
|
import windnd
|
||||||
|
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 ui.widgets import ProgressButton
|
||||||
|
from ui.history_window import record_log
|
||||||
|
|
||||||
|
class BatchTableExtractorApp:
|
||||||
|
def __init__(self, root):
|
||||||
|
self.root = root
|
||||||
|
self.root.title("WordTableExtractor")
|
||||||
|
self.root.geometry("640x520")
|
||||||
|
self.root.minsize(580, 460)
|
||||||
|
|
||||||
|
# 尝试设置窗口图标
|
||||||
|
try:
|
||||||
|
import sys
|
||||||
|
if getattr(sys, 'frozen', False):
|
||||||
|
icon_path = os.path.join(sys._MEIPASS, "app.ico")
|
||||||
|
else:
|
||||||
|
icon_path = os.path.join(APP_DIR, "app.ico")
|
||||||
|
if os.path.exists(icon_path):
|
||||||
|
self.root.iconbitmap(icon_path)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 状态变量
|
||||||
|
self.mode_var = tk.StringVar(value="dir") # "file" 或 "dir"
|
||||||
|
self.src_path_var = tk.StringVar()
|
||||||
|
self.out_dir_var = tk.StringVar()
|
||||||
|
self.recursive_var = tk.BooleanVar(value=False)
|
||||||
|
self.auto_extract_var = tk.BooleanVar(value=False)
|
||||||
|
self.debug_var = tk.BooleanVar(value=False)
|
||||||
|
self.topmost_var = tk.BooleanVar(value=False)
|
||||||
|
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()
|
||||||
|
self._pause_event = threading.Event()
|
||||||
|
self._is_running = False
|
||||||
|
|
||||||
|
self._load_config()
|
||||||
|
self.root.attributes("-topmost", self.topmost_var.get())
|
||||||
|
self._build_ui()
|
||||||
|
self._on_mode_change()
|
||||||
|
|
||||||
|
# 初始化拖拽支持
|
||||||
|
try:
|
||||||
|
windnd.hook_dropfiles(self.root, func=self._on_drop_files)
|
||||||
|
except Exception as e:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 窗口关闭时自动持久化配置
|
||||||
|
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
|
||||||
|
|
||||||
|
def _load_config(self):
|
||||||
|
"""读取本地配置文件"""
|
||||||
|
if os.path.exists(CONFIG_FILE):
|
||||||
|
try:
|
||||||
|
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
|
||||||
|
cfg = json.load(f)
|
||||||
|
self.mode_var.set(cfg.get("mode", "dir"))
|
||||||
|
self.src_path_var.set(cfg.get("src_path", ""))
|
||||||
|
self.out_dir_var.set(cfg.get("out_dir", ""))
|
||||||
|
self.recursive_var.set(cfg.get("recursive", False))
|
||||||
|
self.auto_extract_var.set(cfg.get("auto_extract", False))
|
||||||
|
self.debug_var.set(cfg.get("debug_mode", False))
|
||||||
|
self.topmost_var.set(cfg.get("topmost", False))
|
||||||
|
self.conflict_action_var.set(cfg.get("conflict_action", "直接覆盖 (默认)"))
|
||||||
|
self.pdf_engine_var.set(cfg.get("pdf_engine", "不处理"))
|
||||||
|
self.engine_var.set(cfg.get("engine_var", "自动判断 (推荐)"))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _save_config(self):
|
||||||
|
"""写入配置到本地 JSON"""
|
||||||
|
cfg = {
|
||||||
|
"mode": self.mode_var.get(),
|
||||||
|
"src_path": self.src_path_var.get(),
|
||||||
|
"out_dir": self.out_dir_var.get(),
|
||||||
|
"recursive": self.recursive_var.get(),
|
||||||
|
"auto_extract": self.auto_extract_var.get(),
|
||||||
|
"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()
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(cfg, f, ensure_ascii=False, indent=2)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _build_ui(self):
|
||||||
|
# 移除只读下拉框丑陋的蓝色背景高亮
|
||||||
|
style = ttk.Style()
|
||||||
|
style.map('TCombobox',
|
||||||
|
fieldbackground=[('readonly', 'white')],
|
||||||
|
selectbackground=[('readonly', 'focus', 'white'), ('readonly', 'white')],
|
||||||
|
selectforeground=[('readonly', 'focus', 'black'), ('readonly', 'black')])
|
||||||
|
|
||||||
|
frame = ttk.Frame(self.root, padding="15")
|
||||||
|
frame.pack(fill=tk.BOTH, expand=True)
|
||||||
|
|
||||||
|
# 1. 模式选择
|
||||||
|
mode_box = ttk.LabelFrame(frame, text=" 处理模式 ", padding="8")
|
||||||
|
mode_box.pack(fill=tk.X, pady=(0, 10))
|
||||||
|
|
||||||
|
# 配置列权重以实现更好的分布
|
||||||
|
mode_box.columnconfigure(0, weight=1)
|
||||||
|
mode_box.columnconfigure(1, weight=1)
|
||||||
|
mode_box.columnconfigure(2, weight=1)
|
||||||
|
|
||||||
|
ttk.Radiobutton(mode_box, text="批量处理文件夹", variable=self.mode_var, value="dir",
|
||||||
|
command=self._on_mode_change, takefocus=False).grid(row=0, column=0, sticky=tk.W, padx=10, pady=2)
|
||||||
|
ttk.Radiobutton(mode_box, text="处理单个文件", variable=self.mode_var, value="file",
|
||||||
|
command=self._on_mode_change, takefocus=False).grid(row=0, column=1, sticky=tk.W, padx=10, pady=2)
|
||||||
|
self.chk_recursive = ttk.Checkbutton(mode_box, text="包含子文件夹", variable=self.recursive_var, takefocus=False)
|
||||||
|
self.chk_recursive.grid(row=0, column=2, sticky=tk.W, padx=10, pady=2)
|
||||||
|
|
||||||
|
self.chk_debug = ttk.Checkbutton(mode_box, text="DEBUG", variable=self.debug_var, command=self._on_debug_toggle, takefocus=False)
|
||||||
|
self.chk_debug.grid(row=1, column=0, sticky=tk.W, padx=10, pady=2)
|
||||||
|
self.chk_auto_extract = ttk.Checkbutton(mode_box, text="拖拽后立即提取", variable=self.auto_extract_var, takefocus=False)
|
||||||
|
self.chk_auto_extract.grid(row=1, column=1, sticky=tk.W, padx=10, pady=2)
|
||||||
|
|
||||||
|
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.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.Label(path_box, text="文件冲突:").grid(row=2, column=0, sticky=tk.W, pady=5)
|
||||||
|
|
||||||
|
combo_frame = ttk.Frame(path_box)
|
||||||
|
combo_frame.grid(row=2, column=1, sticky=tk.EW, padx=6)
|
||||||
|
|
||||||
|
def _clear_combo_focus(event):
|
||||||
|
self.root.focus_set()
|
||||||
|
|
||||||
|
cb_conflict = ttk.Combobox(combo_frame, textvariable=self.conflict_action_var, values=["直接覆盖 (默认)", "自动重命名", "直接跳过"], state="readonly", width=18)
|
||||||
|
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)
|
||||||
|
|
||||||
|
path_box.columnconfigure(1, weight=1)
|
||||||
|
|
||||||
|
# 3. 运行操作区
|
||||||
|
btn_frame = ttk.Frame(frame)
|
||||||
|
btn_frame.pack(fill=tk.X, pady=(0, 10))
|
||||||
|
|
||||||
|
self.btn_run = ProgressButton(btn_frame, text="开始全量提取表格", command=self._start)
|
||||||
|
self.btn_run.pack(side=tk.LEFT, fill=tk.X, expand=True)
|
||||||
|
|
||||||
|
# 4. 运行日志窗口
|
||||||
|
log_box = ttk.LabelFrame(frame, text=" 运行日志 ", padding="8")
|
||||||
|
log_box.pack(fill=tk.BOTH, expand=True)
|
||||||
|
|
||||||
|
self.txt = tk.Text(log_box, wrap=tk.WORD, height=8, font=("Consolas", 9))
|
||||||
|
self.txt.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
|
||||||
|
sb = ttk.Scrollbar(log_box, orient=tk.VERTICAL, command=self.txt.yview)
|
||||||
|
sb.pack(side=tk.RIGHT, fill=tk.Y)
|
||||||
|
self.txt.config(yscrollcommand=sb.set)
|
||||||
|
|
||||||
|
# 添加耗时悬浮标签
|
||||||
|
self.lbl_timer = tk.Label(self.txt, text="00:00:00.000", font=("Consolas", 10), bg="white", fg="gray")
|
||||||
|
self.lbl_timer.place(relx=1.0, rely=0.0, anchor=tk.NE, x=-10, y=5)
|
||||||
|
|
||||||
|
def _on_debug_toggle(self):
|
||||||
|
if self.debug_var.get():
|
||||||
|
messagebox.showinfo("Debug 模式说明", "开启 Debug 模式后,程序在提取表格时将强制显示 Office/WPS 窗口。\n\n这主要用于排查程序“卡死”的问题。例如:当文档被加密或需要修复时,Office 会在后台弹窗等待用户点击。开启此模式可让你看到这些弹窗并手动处理。")
|
||||||
|
|
||||||
|
def _on_topmost_toggle(self):
|
||||||
|
self.root.attributes("-topmost", self.topmost_var.get())
|
||||||
|
|
||||||
|
def _stop_task(self):
|
||||||
|
self._pause_event.set()
|
||||||
|
ans = messagebox.askyesno("确认", "任务已暂停。\n\n是否确定终止批量提取操作?\n(选择“是”终止操作,选择“否”继续提取)")
|
||||||
|
if ans:
|
||||||
|
self._stop_event.set()
|
||||||
|
self.btn_run.config_btn(state=tk.DISABLED, text="正在终止...")
|
||||||
|
self.log("\n⚠️ 正在尝试终止任务,请等待当前文件处理完毕...")
|
||||||
|
self._pause_event.clear()
|
||||||
|
|
||||||
|
def _on_mode_change(self):
|
||||||
|
if self.mode_var.get() == "dir":
|
||||||
|
self.lbl_src.config(text="来源目录:")
|
||||||
|
self.chk_recursive.config(state=tk.NORMAL)
|
||||||
|
else:
|
||||||
|
self.lbl_src.config(text="来源文件:")
|
||||||
|
self.chk_recursive.config(state=tk.DISABLED)
|
||||||
|
|
||||||
|
def _browse_src(self):
|
||||||
|
if self.mode_var.get() == "dir":
|
||||||
|
path = filedialog.askdirectory(title="选择包含文档的目录")
|
||||||
|
else:
|
||||||
|
path = filedialog.askopenfilename(
|
||||||
|
title="选择文档",
|
||||||
|
filetypes=[("支持的文档", "*.doc *.docx *.pdf *.png *.jpg *.jpeg"), ("所有文件", "*.*")]
|
||||||
|
)
|
||||||
|
if path:
|
||||||
|
path = os.path.normpath(path)
|
||||||
|
self.src_path_var.set(path)
|
||||||
|
if not self.out_dir_var.get().strip():
|
||||||
|
base_dir = path if self.mode_var.get() == "dir" else os.path.dirname(path)
|
||||||
|
self.out_dir_var.set(os.path.normpath(os.path.join(base_dir, "convert")))
|
||||||
|
|
||||||
|
def _browse_out(self):
|
||||||
|
path = filedialog.askdirectory(title="选择输出目录")
|
||||||
|
if path:
|
||||||
|
self.out_dir_var.set(os.path.normpath(path))
|
||||||
|
|
||||||
|
def _on_drop_files(self, files):
|
||||||
|
if not files:
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
# windnd 返回的通常是 gbk 编码的字节串
|
||||||
|
dropped_paths = [f.decode("gbk") for f in files]
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
dropped_paths = [f.decode("utf-8") for f in files]
|
||||||
|
except Exception:
|
||||||
|
return
|
||||||
|
|
||||||
|
if not dropped_paths:
|
||||||
|
return
|
||||||
|
|
||||||
|
if len(dropped_paths) > 1:
|
||||||
|
messagebox.showinfo("提示", "目前仅支持单次拖拽一个文件或文件夹。系统将仅读取拖入的第一个项目!")
|
||||||
|
|
||||||
|
first_path = dropped_paths[0]
|
||||||
|
|
||||||
|
if os.path.isdir(first_path):
|
||||||
|
self.mode_var.set("dir")
|
||||||
|
self._on_mode_change()
|
||||||
|
self.src_path_var.set(os.path.normpath(first_path))
|
||||||
|
if not self.out_dir_var.get().strip():
|
||||||
|
self.out_dir_var.set(os.path.normpath(os.path.join(first_path, "convert")))
|
||||||
|
elif os.path.isfile(first_path):
|
||||||
|
self.mode_var.set("file")
|
||||||
|
self._on_mode_change()
|
||||||
|
self.src_path_var.set(os.path.normpath(first_path))
|
||||||
|
if not self.out_dir_var.get().strip():
|
||||||
|
self.out_dir_var.set(os.path.normpath(os.path.join(os.path.dirname(first_path), "convert")))
|
||||||
|
|
||||||
|
if self.auto_extract_var.get():
|
||||||
|
self.root.after(100, self._start)
|
||||||
|
|
||||||
|
def _show_log_window(self):
|
||||||
|
from ui.history_window import show_history_log_window
|
||||||
|
show_history_log_window(self.root, self.topmost_var.get())
|
||||||
|
|
||||||
|
def log(self, msg, tag=None):
|
||||||
|
self.txt.tag_config("error", foreground="red")
|
||||||
|
self.txt.tag_config("highlight", foreground="red")
|
||||||
|
if tag:
|
||||||
|
self.txt.insert(tk.END, f"{msg}\n", tag)
|
||||||
|
elif "跳过" in msg or "❌" in msg or "失败" in msg:
|
||||||
|
self.txt.insert(tk.END, f"{msg}\n", "error")
|
||||||
|
else:
|
||||||
|
self.txt.insert(tk.END, f"{msg}\n")
|
||||||
|
self.txt.see(tk.END)
|
||||||
|
|
||||||
|
def _on_close(self):
|
||||||
|
if getattr(self, '_is_running', False):
|
||||||
|
self._pause_event.set()
|
||||||
|
ans = messagebox.askyesno("确认退出", "当前正在提取表格,强制退出可能会导致部分文件提取不完整。\n\n是否确定要退出程序?")
|
||||||
|
if not ans:
|
||||||
|
self._pause_event.clear()
|
||||||
|
return
|
||||||
|
self._stop_event.set()
|
||||||
|
|
||||||
|
self._save_config()
|
||||||
|
self.root.destroy()
|
||||||
|
|
||||||
|
def _update_timer(self):
|
||||||
|
if not getattr(self, '_is_running', False):
|
||||||
|
return
|
||||||
|
|
||||||
|
if self._pause_event.is_set():
|
||||||
|
if not getattr(self, '_is_paused_now', False):
|
||||||
|
self._is_paused_now = True
|
||||||
|
self._pause_start = time.time()
|
||||||
|
else:
|
||||||
|
if getattr(self, '_is_paused_now', False):
|
||||||
|
self._is_paused_now = False
|
||||||
|
self._start_time += (time.time() - self._pause_start)
|
||||||
|
|
||||||
|
elapsed = time.time() - getattr(self, '_start_time', time.time())
|
||||||
|
hours, rem = divmod(elapsed, 3600)
|
||||||
|
minutes, seconds = divmod(rem, 60)
|
||||||
|
ms = int((elapsed - int(elapsed)) * 1000)
|
||||||
|
time_str = f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}.{ms:03d}"
|
||||||
|
self.lbl_timer.config(text=time_str)
|
||||||
|
|
||||||
|
self.root.after(50, self._update_timer)
|
||||||
|
|
||||||
|
def _start(self):
|
||||||
|
self._save_config()
|
||||||
|
src = self.src_path_var.get().strip()
|
||||||
|
out = self.out_dir_var.get().strip()
|
||||||
|
mode = self.mode_var.get()
|
||||||
|
recursive = self.recursive_var.get()
|
||||||
|
|
||||||
|
if not src or not os.path.exists(src):
|
||||||
|
messagebox.showwarning("提示", "请选择有效的来源文件或目录!")
|
||||||
|
return
|
||||||
|
|
||||||
|
if not out:
|
||||||
|
messagebox.showwarning("提示", "请选择有效的输出目录!")
|
||||||
|
return
|
||||||
|
|
||||||
|
if not os.path.exists(out):
|
||||||
|
try:
|
||||||
|
os.makedirs(out)
|
||||||
|
except Exception as e:
|
||||||
|
messagebox.showwarning("提示", f"无法创建输出目录: {e}")
|
||||||
|
return
|
||||||
|
elif not os.path.isdir(out):
|
||||||
|
messagebox.showwarning("提示", "转换目录路径已被文件占用!")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 收集目标文件列表
|
||||||
|
files_to_process = []
|
||||||
|
if mode == "file":
|
||||||
|
if src.lower().endswith(('.doc', '.docx', '.pdf', '.png', '.jpg', '.jpeg')):
|
||||||
|
files_to_process.append(src)
|
||||||
|
else:
|
||||||
|
pattern = "**/*" if recursive else "*"
|
||||||
|
for ext in ("*.doc", "*.docx", "*.pdf", "*.png", "*.jpg", "*.jpeg"):
|
||||||
|
full_pattern = os.path.join(src, pattern, ext) if recursive else os.path.join(src, ext)
|
||||||
|
files_to_process.extend(glob.glob(full_pattern, recursive=recursive))
|
||||||
|
|
||||||
|
# 排除 office 生成的临时文件 (~$开头)
|
||||||
|
files_to_process = [f for f in files_to_process if not os.path.basename(f).startswith("~$")]
|
||||||
|
|
||||||
|
if not files_to_process:
|
||||||
|
messagebox.showinfo("提示", "未找到任何待处理的文档或图片!")
|
||||||
|
return
|
||||||
|
|
||||||
|
self.btn_run.config_btn(text="启动中... ", command=self._stop_task)
|
||||||
|
self.btn_run.set_progress(0.0)
|
||||||
|
self._stop_event.clear()
|
||||||
|
self._is_running = True
|
||||||
|
|
||||||
|
self.log(f"\n===== 开始任务: 共扫描到 {len(files_to_process)} 个文件 =====")
|
||||||
|
|
||||||
|
self._start_time = time.time()
|
||||||
|
self._update_timer()
|
||||||
|
|
||||||
|
threading.Thread(
|
||||||
|
target=self._worker,
|
||||||
|
args=(files_to_process, out),
|
||||||
|
daemon=True
|
||||||
|
).start()
|
||||||
|
|
||||||
|
def _generate_batch_id(self):
|
||||||
|
date_str = datetime.datetime.now().strftime("%y%m%d")
|
||||||
|
log_path = os.path.join(APP_DIR, "conversion.csv")
|
||||||
|
seq = 1
|
||||||
|
if os.path.exists(log_path):
|
||||||
|
try:
|
||||||
|
import csv
|
||||||
|
with open(log_path, "r", encoding="utf-8-sig") as f:
|
||||||
|
reader = csv.reader(f)
|
||||||
|
for row in reader:
|
||||||
|
if row and row[0].startswith(f"{date_str}X"):
|
||||||
|
try:
|
||||||
|
current_seq = int(row[0].split("X")[1])
|
||||||
|
if current_seq >= seq:
|
||||||
|
seq = current_seq + 1
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
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()
|
||||||
|
|
||||||
|
total = len(file_list)
|
||||||
|
for idx, file_path in enumerate(file_list, start=1):
|
||||||
|
if self._pause_event.is_set():
|
||||||
|
self.root.after(0, lambda: self.btn_run.config_btn(text="任务已暂停..."))
|
||||||
|
import time
|
||||||
|
while self._pause_event.is_set():
|
||||||
|
time.sleep(0.1)
|
||||||
|
|
||||||
|
if self._stop_event.is_set():
|
||||||
|
self.root.after(0, lambda: self.log("\n❌ 任务已被用户手动终止!"))
|
||||||
|
break
|
||||||
|
|
||||||
|
base_name = os.path.splitext(os.path.basename(file_path))[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}"))
|
||||||
|
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} | 点击终止操作")
|
||||||
|
self.btn_run.set_progress(i / t)
|
||||||
|
self.root.after(0, update_skip_btn)
|
||||||
|
continue
|
||||||
|
elif conflict_action == "自动重命名":
|
||||||
|
counter = 1
|
||||||
|
while True:
|
||||||
|
new_name = f"{base_name}_表格_{counter}.xlsx"
|
||||||
|
target_excel = os.path.join(out_dir, new_name)
|
||||||
|
if not os.path.exists(target_excel):
|
||||||
|
break
|
||||||
|
counter += 1
|
||||||
|
|
||||||
|
self.root.after(0, lambda i=idx, t=total, name=base_name: self.log(f"[{i}/{t}] 处理中: {name}"))
|
||||||
|
import time
|
||||||
|
t0 = time.time()
|
||||||
|
try:
|
||||||
|
def my_log(m):
|
||||||
|
self.root.after(0, self.log, m)
|
||||||
|
|
||||||
|
ext = os.path.splitext(file_path)[1].lower()
|
||||||
|
route_target = "word"
|
||||||
|
|
||||||
|
if ext in ['.png', '.jpg', '.jpeg']:
|
||||||
|
route_target = "ocr"
|
||||||
|
elif ext == '.pdf':
|
||||||
|
engine_pref = self.pdf_engine_var.get()
|
||||||
|
if "不处理" in engine_pref:
|
||||||
|
self.root.after(0, lambda: self.log(" [跳过] 用户设置 PDF 不处理"))
|
||||||
|
record_log(batch_id, "跳过", base_name, "-", 0, 0.0, file_path, "PDF设置为不处理")
|
||||||
|
def update_skip_btn(i=idx, t=total):
|
||||||
|
self.btn_run.config_btn(text=f"提取中 {i}/{t} | 点击终止操作")
|
||||||
|
self.btn_run.set_progress(i / t)
|
||||||
|
self.root.after(0, update_skip_btn)
|
||||||
|
continue
|
||||||
|
elif "Word" in engine_pref:
|
||||||
|
route_target = "word"
|
||||||
|
elif "本地 AI" in engine_pref or "OCR" in engine_pref:
|
||||||
|
route_target = "ocr"
|
||||||
|
else:
|
||||||
|
# 智能判定:读取前3页文本量
|
||||||
|
try:
|
||||||
|
import fitz
|
||||||
|
with fitz.open(file_path) as pdoc:
|
||||||
|
text_len = 0
|
||||||
|
check_pages = min(3, len(pdoc))
|
||||||
|
for p in range(check_pages):
|
||||||
|
text_len += len(pdoc[p].get_text("text").strip())
|
||||||
|
|
||||||
|
if text_len > 100:
|
||||||
|
self.root.after(0, lambda: self.log(" [智能判定] 识别为电子版 PDF,已路由至 Word 极速引擎"))
|
||||||
|
route_target = "word"
|
||||||
|
else:
|
||||||
|
self.root.after(0, lambda: self.log(" [智能判定] 识别为扫描版 PDF,已路由至云端 OCR 引擎"))
|
||||||
|
route_target = "ocr"
|
||||||
|
except Exception:
|
||||||
|
route_target = "ocr" # fallback
|
||||||
|
|
||||||
|
if route_target == "word":
|
||||||
|
ensure_apps()
|
||||||
|
tc = export_single_doc_tables(word_app, excel_app, file_path, target_excel,
|
||||||
|
log_func=my_log, debug=debug_mode)
|
||||||
|
else:
|
||||||
|
from core.extractor import export_pdf_image_tables_local
|
||||||
|
tc = export_pdf_image_tables_local(None, file_path, target_excel, "",
|
||||||
|
log_func=my_log, debug=debug_mode)
|
||||||
|
|
||||||
|
duration = time.time() - t0
|
||||||
|
if tc > 0:
|
||||||
|
success_count += 1
|
||||||
|
record_log(batch_id, "成功", base_name, f"{base_name}_表格.xlsx", tc, duration, file_path, "提取完成")
|
||||||
|
else:
|
||||||
|
record_log(batch_id, "跳过", base_name, "-", 0, duration, file_path, "未检测到表格")
|
||||||
|
except Exception as e:
|
||||||
|
duration = time.time() - t0
|
||||||
|
import traceback
|
||||||
|
trace_str = traceback.format_exc()
|
||||||
|
if self.debug_var.get():
|
||||||
|
err_msg = f" ❌ 失败跳过 [{base_name}]: {e}\n{trace_str}"
|
||||||
|
else:
|
||||||
|
err_msg = f" ❌ 失败跳过 [{base_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}")
|
||||||
|
|
||||||
|
# 更新按钮文字进度
|
||||||
|
def update_btn(i=idx, t=total):
|
||||||
|
self.btn_run.config_btn(text=f"提取中 {i}/{t} | 点击终止操作")
|
||||||
|
self.btn_run.set_progress(i / t)
|
||||||
|
self.root.after(0, update_btn)
|
||||||
|
|
||||||
|
self.root.after(0, lambda: self.log(f"\n===== 处理完成!成功导出 {success_count}/{total} 个文档的表格 =====\n", tag="highlight"))
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
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)
|
||||||
|
self._is_running = False
|
||||||
|
self.root.after(0, _reset_btn)
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import os
|
||||||
|
import csv
|
||||||
|
import datetime
|
||||||
|
import tkinter as tk
|
||||||
|
from tkinter import ttk, messagebox
|
||||||
|
from utils.config import APP_DIR
|
||||||
|
|
||||||
|
def record_log(batch_id, status, doc_name, excel_name, table_count, duration, src_path, message):
|
||||||
|
log_path = os.path.join(APP_DIR, "conversion.csv")
|
||||||
|
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
try:
|
||||||
|
file_exists = os.path.exists(log_path)
|
||||||
|
with open(log_path, "a", encoding="utf-8-sig", newline="") as f:
|
||||||
|
writer = csv.writer(f)
|
||||||
|
if not file_exists:
|
||||||
|
writer.writerow(["任务批次", "处理时间", "耗时(秒)", "来源文档", "导出文件", "表格数量", "处理状态", "原文档路径", "备注详情"])
|
||||||
|
writer.writerow([batch_id, now, f"{duration:.3f}", doc_name, excel_name, str(table_count), status, src_path, message])
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
class HistoryLogWindow:
|
||||||
|
def __init__(self, parent, is_topmost=False):
|
||||||
|
self.parent = parent
|
||||||
|
self.is_topmost = is_topmost
|
||||||
|
self._show()
|
||||||
|
|
||||||
|
def _show(self):
|
||||||
|
log_path = os.path.join(APP_DIR, "conversion.csv")
|
||||||
|
if not os.path.exists(log_path):
|
||||||
|
messagebox.showinfo("提示", "目前还没有历史日志。")
|
||||||
|
return
|
||||||
|
|
||||||
|
win = tk.Toplevel(self.parent)
|
||||||
|
win.title("历史转换日志")
|
||||||
|
win.geometry("900x500")
|
||||||
|
if self.is_topmost:
|
||||||
|
win.attributes("-topmost", True)
|
||||||
|
|
||||||
|
filter_frame = ttk.Frame(win, padding=10)
|
||||||
|
filter_frame.pack(fill=tk.X)
|
||||||
|
|
||||||
|
ttk.Label(filter_frame, text="按状态筛选:").pack(side=tk.LEFT)
|
||||||
|
filter_var = tk.StringVar(value="全部")
|
||||||
|
filter_cb = ttk.Combobox(filter_frame, textvariable=filter_var, values=["全部", "仅成功", "仅失败/跳过"], state="readonly", width=15)
|
||||||
|
filter_cb.pack(side=tk.LEFT, padx=10)
|
||||||
|
|
||||||
|
columns = ("batch", "time", "duration", "doc", "excel", "tables", "status", "path", "msg")
|
||||||
|
tree = ttk.Treeview(win, columns=columns, show="headings")
|
||||||
|
|
||||||
|
def sort_treeview(tv, col, reverse):
|
||||||
|
l = [(tv.set(k, col), k) for k in tv.get_children('')]
|
||||||
|
def convert(val):
|
||||||
|
try: return float(val)
|
||||||
|
except ValueError: return val
|
||||||
|
l.sort(key=lambda t: convert(t[0]), reverse=reverse)
|
||||||
|
for index, (val, k) in enumerate(l):
|
||||||
|
tv.move(k, '', index)
|
||||||
|
tv.heading(col, command=lambda: sort_treeview(tv, col, not reverse))
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"batch": ("任务批次", 100, tk.CENTER),
|
||||||
|
"time": ("处理时间", 140, tk.CENTER),
|
||||||
|
"duration": ("耗时", 50, tk.CENTER),
|
||||||
|
"doc": ("来源文档", 130, tk.W),
|
||||||
|
"excel": ("导出文件", 130, tk.W),
|
||||||
|
"tables": ("表格数", 50, tk.CENTER),
|
||||||
|
"status": ("状态", 50, tk.CENTER),
|
||||||
|
"path": ("原文件路径", 180, tk.W),
|
||||||
|
"msg": ("备注详情", 180, tk.W)
|
||||||
|
}
|
||||||
|
|
||||||
|
for col, (text, width, anchor) in headers.items():
|
||||||
|
tree.heading(col, text=text, command=lambda c=col: sort_treeview(tree, c, False))
|
||||||
|
tree.column(col, width=width, anchor=anchor)
|
||||||
|
|
||||||
|
tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
|
||||||
|
sb = ttk.Scrollbar(win, orient=tk.VERTICAL, command=tree.yview)
|
||||||
|
sb.pack(side=tk.RIGHT, fill=tk.Y)
|
||||||
|
tree.config(yscrollcommand=sb.set)
|
||||||
|
|
||||||
|
tree.tag_configure("error", foreground="red")
|
||||||
|
|
||||||
|
with open(log_path, "r", encoding="utf-8-sig") as f:
|
||||||
|
reader = csv.reader(f)
|
||||||
|
header = next(reader, None)
|
||||||
|
all_rows = list(reader)
|
||||||
|
all_rows.reverse()
|
||||||
|
|
||||||
|
def update_log_view(event=None):
|
||||||
|
for item in tree.get_children():
|
||||||
|
tree.delete(item)
|
||||||
|
f_val = filter_var.get()
|
||||||
|
|
||||||
|
for row in all_rows:
|
||||||
|
if len(row) < 6: continue
|
||||||
|
if len(row) == 6:
|
||||||
|
batch, t, doc, exc, status, msg = row
|
||||||
|
dur, tables, pth = "0.0", "0", ""
|
||||||
|
else:
|
||||||
|
batch, t, dur, doc, exc, tables, status, pth, msg = row[:9]
|
||||||
|
|
||||||
|
is_error = status in ("失败", "跳过")
|
||||||
|
is_success = status == "成功"
|
||||||
|
|
||||||
|
if f_val == "仅成功" and not is_success:
|
||||||
|
continue
|
||||||
|
if f_val == "仅失败/跳过" and not is_error:
|
||||||
|
continue
|
||||||
|
|
||||||
|
tag = "error" if is_error else ()
|
||||||
|
tree.insert("", tk.END, values=(batch, t, dur, doc, exc, tables, status, pth, msg), tags=tag)
|
||||||
|
|
||||||
|
filter_cb.bind("<<ComboboxSelected>>", update_log_view)
|
||||||
|
update_log_view()
|
||||||
|
|
||||||
|
def on_double_click(event):
|
||||||
|
item = tree.selection()
|
||||||
|
if not item: return
|
||||||
|
item = item[0]
|
||||||
|
values = tree.item(item, "values")
|
||||||
|
if not values: return
|
||||||
|
msg = values[8]
|
||||||
|
|
||||||
|
detail_win = tk.Toplevel(win)
|
||||||
|
detail_win.title("详细信息")
|
||||||
|
detail_win.geometry("500x300")
|
||||||
|
if self.is_topmost:
|
||||||
|
detail_win.attributes("-topmost", True)
|
||||||
|
|
||||||
|
txt = tk.Text(detail_win, wrap=tk.WORD, font=("Consolas", 9))
|
||||||
|
txt.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
|
||||||
|
txt.insert(tk.END, msg)
|
||||||
|
txt.config(state=tk.DISABLED)
|
||||||
|
|
||||||
|
tree.bind("<Double-1>", on_double_click)
|
||||||
|
|
||||||
|
def show_history_log_window(parent, is_topmost):
|
||||||
|
HistoryLogWindow(parent, is_topmost)
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import tkinter as tk
|
||||||
|
|
||||||
|
class ProgressButton(tk.Canvas):
|
||||||
|
def __init__(self, master, text="", command=None, **kwargs):
|
||||||
|
bg = kwargs.pop('bg', '#e1e1e1')
|
||||||
|
height = kwargs.pop('height', 32)
|
||||||
|
cursor = kwargs.pop('cursor', 'hand2')
|
||||||
|
super().__init__(master, bg=bg, highlightthickness=1, highlightbackground="#cccccc", highlightcolor="#cccccc", height=height, cursor=cursor, **kwargs)
|
||||||
|
self.command = command
|
||||||
|
self.progress = 0.0
|
||||||
|
|
||||||
|
self.bg_color = bg
|
||||||
|
self.fill_color = "#4caf50"
|
||||||
|
self.hover_color = "#d5d5d5"
|
||||||
|
|
||||||
|
self.rect_id = self.create_rectangle(0, 0, 0, 0, fill=self.fill_color, width=0)
|
||||||
|
self.text_id = self.create_text(0, 0, text=text, fill="black", font=("Microsoft YaHei", 10))
|
||||||
|
|
||||||
|
self.bind("<Button-1>", self._on_click)
|
||||||
|
self.bind("<Enter>", self._on_enter)
|
||||||
|
self.bind("<Leave>", self._on_leave)
|
||||||
|
self.bind("<Configure>", self._on_resize)
|
||||||
|
|
||||||
|
def _on_click(self, event):
|
||||||
|
if self.command:
|
||||||
|
self.command()
|
||||||
|
|
||||||
|
def _on_enter(self, event):
|
||||||
|
self.config(bg=self.hover_color)
|
||||||
|
|
||||||
|
def _on_leave(self, event):
|
||||||
|
self.config(bg=self.bg_color)
|
||||||
|
|
||||||
|
def _on_resize(self, event):
|
||||||
|
self._update_layout()
|
||||||
|
|
||||||
|
def _update_layout(self):
|
||||||
|
w = self.winfo_width()
|
||||||
|
h = self.winfo_height()
|
||||||
|
self.coords(self.rect_id, 0, 0, w * self.progress, h)
|
||||||
|
self.coords(self.text_id, w / 2, h / 2)
|
||||||
|
|
||||||
|
def config_btn(self, text=None, command=None, state=None):
|
||||||
|
if text is not None:
|
||||||
|
self.itemconfig(self.text_id, text=text)
|
||||||
|
if command is not None:
|
||||||
|
self.command = command
|
||||||
|
if state == tk.DISABLED:
|
||||||
|
self.config(cursor="arrow", bg=self.bg_color)
|
||||||
|
self.unbind("<Button-1>")
|
||||||
|
self.unbind("<Enter>")
|
||||||
|
self.unbind("<Leave>")
|
||||||
|
elif state == tk.NORMAL:
|
||||||
|
self.config(cursor="hand2")
|
||||||
|
self.bind("<Button-1>", self._on_click)
|
||||||
|
self.bind("<Enter>", self._on_enter)
|
||||||
|
self.bind("<Leave>", self._on_leave)
|
||||||
|
|
||||||
|
def set_progress(self, percent):
|
||||||
|
self.progress = percent
|
||||||
|
self._update_layout()
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# 兼容 Python 3.13 动态加载系统目录
|
||||||
|
pywin32_dir = os.path.join(sys.prefix, "Lib", "site-packages", "pywin32_system32")
|
||||||
|
if os.path.exists(pywin32_dir):
|
||||||
|
try:
|
||||||
|
os.add_dll_directory(pywin32_dir)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# ---------------- 获取运行与配置目录 ----------------
|
||||||
|
if getattr(sys, 'frozen', False):
|
||||||
|
# 打包为 exe 后:与 exe 同级
|
||||||
|
APP_DIR = os.path.dirname(sys.executable)
|
||||||
|
else:
|
||||||
|
# 源码开发调试:定位到 src 的上一层(项目根目录)
|
||||||
|
APP_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
|
CONFIG_FILE = os.path.join(APP_DIR, "config.json")
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
import sys
|
||||||
|
import os
|
||||||
|
import argparse
|
||||||
|
import numpy as np
|
||||||
|
from PIL import Image
|
||||||
|
import pandas as pd
|
||||||
|
import io
|
||||||
|
import fitz
|
||||||
|
import cv2
|
||||||
|
from rapid_table import RapidTable
|
||||||
|
from rapidocr_onnxruntime import RapidOCR
|
||||||
|
|
||||||
|
class OcrResultObj:
|
||||||
|
def __init__(self, res):
|
||||||
|
self.boxes = None
|
||||||
|
self.txts = None
|
||||||
|
self.scores = None
|
||||||
|
if res:
|
||||||
|
self.boxes = [r[0] for r in res]
|
||||||
|
self.txts = [r[1] for r in res]
|
||||||
|
self.scores = [float(r[2]) for r in res]
|
||||||
|
|
||||||
|
class CustomOcrEngine:
|
||||||
|
def __init__(self):
|
||||||
|
self.engine = RapidOCR()
|
||||||
|
def __call__(self, img, **kwargs):
|
||||||
|
res, _ = self.engine(img)
|
||||||
|
return OcrResultObj(res)
|
||||||
|
|
||||||
|
def parse_page_ranges(pages_str, total_pages):
|
||||||
|
if not pages_str:
|
||||||
|
return list(range(total_pages))
|
||||||
|
pages = set()
|
||||||
|
for part in pages_str.split(','):
|
||||||
|
part = part.strip()
|
||||||
|
if not part: continue
|
||||||
|
if '-' in part:
|
||||||
|
try:
|
||||||
|
start, end = part.split('-')
|
||||||
|
start = max(1, int(start))
|
||||||
|
end = min(total_pages, int(end))
|
||||||
|
pages.update(range(start - 1, end))
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
p = int(part)
|
||||||
|
if 1 <= p <= total_pages:
|
||||||
|
pages.add(p - 1)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
return sorted(list(pages)) if pages else list(range(total_pages))
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("img_path", help="Path to input PDF or Image")
|
||||||
|
parser.add_argument("excel_path", help="Path to output Excel file")
|
||||||
|
parser.add_argument("--pages", default="", help="Page ranges, e.g. 1,3,5-8")
|
||||||
|
parser.add_argument("--debug", action="store_true", help="Enable detailed debug logs")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
img_path = args.img_path
|
||||||
|
excel_path = args.excel_path
|
||||||
|
is_debug = args.debug
|
||||||
|
|
||||||
|
if not os.path.exists(img_path):
|
||||||
|
print(f"Error: File not found {img_path}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
table_engine = RapidTable()
|
||||||
|
table_engine.ocr_engine = CustomOcrEngine()
|
||||||
|
|
||||||
|
images = [] # (page_num, image_numpy_array)
|
||||||
|
ext = os.path.splitext(img_path)[1].lower()
|
||||||
|
|
||||||
|
if ext == '.pdf':
|
||||||
|
doc = fitz.open(img_path)
|
||||||
|
page_indices = parse_page_ranges(args.pages, len(doc))
|
||||||
|
print(f"[PDF] Processing {len(page_indices)} pages...")
|
||||||
|
for p_idx in page_indices:
|
||||||
|
page = doc[p_idx]
|
||||||
|
pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
|
||||||
|
img_array = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.h, pix.w, pix.n)
|
||||||
|
if pix.n == 4:
|
||||||
|
img_array = cv2.cvtColor(img_array, cv2.COLOR_RGBA2RGB)
|
||||||
|
elif pix.n == 1:
|
||||||
|
img_array = cv2.cvtColor(img_array, cv2.COLOR_GRAY2RGB)
|
||||||
|
images.append((p_idx + 1, img_array))
|
||||||
|
doc.close()
|
||||||
|
else:
|
||||||
|
img_array = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), cv2.IMREAD_COLOR)
|
||||||
|
images.append((1, img_array))
|
||||||
|
|
||||||
|
if not images:
|
||||||
|
print("No images to process.")
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
tables_found = 0
|
||||||
|
extracted_tables = []
|
||||||
|
|
||||||
|
total_images = len(images)
|
||||||
|
for page_num, img_array in images:
|
||||||
|
print(f"[OCR] 正在扫描第 {page_num} 页, 共 {total_images} 页...")
|
||||||
|
import time
|
||||||
|
start_time = time.time()
|
||||||
|
try:
|
||||||
|
table_result = table_engine(img_array)
|
||||||
|
if is_debug:
|
||||||
|
print(f" [Debug] 第 {page_num} 页 AI 推理耗时: {time.time() - start_time:.3f}s")
|
||||||
|
|
||||||
|
if hasattr(table_result, 'pred_htmls') and table_result.pred_htmls:
|
||||||
|
for html_idx, html_str in enumerate(table_result.pred_htmls):
|
||||||
|
if html_str:
|
||||||
|
if is_debug:
|
||||||
|
print(f" [Debug] 第 {page_num} 页生成 HTML 代码,长度: {len(html_str)}")
|
||||||
|
try:
|
||||||
|
dfs = pd.read_html(io.StringIO(html_str))
|
||||||
|
for i, df in enumerate(dfs):
|
||||||
|
tables_found += 1
|
||||||
|
sheet_name = f"P{page_num}_T{i+1}"
|
||||||
|
extracted_tables.append((sheet_name, df))
|
||||||
|
if is_debug:
|
||||||
|
print(f" [Debug] 第 {page_num} 页保存表格 {i+1}: {df.shape[0]} 行, {df.shape[1]} 列")
|
||||||
|
except ValueError as e:
|
||||||
|
if "No tables found" not in str(e):
|
||||||
|
print(f"Error parsing html on page {page_num}: {e}")
|
||||||
|
else:
|
||||||
|
# Fallback if old rapid_table version returned a string directly
|
||||||
|
if isinstance(table_result, str):
|
||||||
|
try:
|
||||||
|
dfs = pd.read_html(io.StringIO(table_result))
|
||||||
|
for i, df in enumerate(dfs):
|
||||||
|
tables_found += 1
|
||||||
|
sheet_name = f"P{page_num}_T{i+1}"
|
||||||
|
extracted_tables.append((sheet_name, df))
|
||||||
|
except ValueError as e:
|
||||||
|
pass
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error processing page {page_num}: {e}")
|
||||||
|
|
||||||
|
if not extracted_tables:
|
||||||
|
print("No tables detected.")
|
||||||
|
if os.path.exists(excel_path):
|
||||||
|
os.remove(excel_path)
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
with pd.ExcelWriter(excel_path, engine='openpyxl') as writer:
|
||||||
|
for sheet_name, df in extracted_tables:
|
||||||
|
df.to_excel(writer, sheet_name=sheet_name, index=False, header=False)
|
||||||
|
|
||||||
|
print(f"Successfully extracted {tables_found} tables.")
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user