Files
T

106 lines
3.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""XQ0033 插件 - WPS/Excel COM 全量重算 + 取消筛选。
openpyxl 覆盖保存后公式缓存丢失,必须经 COM 全量重算并保存,后续 data_only 读取才有值。
引擎按 Ket.Application(WPS)→ et.Application(旧版 WPS)→ Excel.Application 兜底;
目标文件已在 WPS/Excel 中打开时复用该工作簿,不关闭、不退出用户实例。
"""
import os
from .. import config
class ComRecalcError(RuntimeError):
"""公式重算失败(无可用 COM 引擎 / 文件被锁定 / COM 异常)。"""
def recalc_target(file_path):
"""对 xlsx 执行「取消全部筛选 → 全量重算公式 → 保存」。"""
file_path = os.path.abspath(file_path)
if not os.path.isfile(file_path):
raise ComRecalcError(f"待重算文件不存在:{file_path}")
import pythoncom
import win32com.client
pythoncom.CoInitialize()
app = None
prog_id = ""
wb = None
already_open = False
try:
last_err = None
for pid in config.COM_PROG_IDS:
try:
app = win32com.client.Dispatch(pid)
prog_id = pid
break
except Exception as e:
last_err = e
if app is None:
raise ComRecalcError(
"本机未检测到可用的 WPS/Excel COM(依次尝试 "
+ " / ".join(config.COM_PROG_IDS) + f" 均失败):{last_err}")
try:
app.DisplayAlerts = False
for w in app.Workbooks:
try:
if os.path.normcase(str(w.FullName or "")) == os.path.normcase(file_path):
wb = w
already_open = True
break
except Exception:
continue
if wb is None:
wb = app.Workbooks.Open(file_path)
removed = 0
for ws in wb.Worksheets:
try:
if ws.AutoFilterMode:
ws.AutoFilterMode = False
removed += 1
except Exception:
pass
try:
wb.Application.CalculateFullRebuild()
except Exception:
try:
wb.Application.CalculateFull()
except Exception:
wb.Application.Calculate()
wb.Save()
config.logger.info("COM 处理完成(%s):取消 %d 个 sheet 筛选,公式全量重算并保存%s",
prog_id, removed,
"(复用已打开的工作簿)" if already_open else "")
finally:
try:
app.DisplayAlerts = True
except Exception:
pass
if wb is not None and not already_open:
try:
wb.Close(SaveChanges=False)
except Exception:
pass
except ComRecalcError:
raise
except Exception as e:
raise ComRecalcError(
f"公式重算失败({prog_id or 'COM'}):{e}\n"
"请确认该目标文件未被 WPS/Excel 以受保护/只读视图打开(关闭后再试)。") from e
finally:
if app is not None:
try:
if app.Workbooks.Count == 0:
app.Quit()
except Exception:
pass
try:
pythoncom.CoUninitialize()
except Exception:
pass