v1
This commit is contained in:
+344
@@ -0,0 +1,344 @@
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import glob
|
||||
import threading
|
||||
import tkinter as tk
|
||||
from tkinter import filedialog, messagebox, ttk
|
||||
|
||||
# 兼容 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
|
||||
|
||||
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__":
|
||||
app_root = tk.Tk()
|
||||
app = BatchTableExtractorApp(app_root)
|
||||
app_root.mainloop()
|
||||
Reference in New Issue
Block a user