144 lines
5.0 KiB
Python
144 lines
5.0 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""用 WPS/Excel COM 真正刷新透视表 + 重算公式缓存(本地副本)。
|
||
|
||
项目里已有成熟模式(XQ0037 / XQ0052):优先 ``Ket.Application``(WPS 表格),
|
||
失败退 ``Excel.Application``。只刷新本地过程表副本,不碰共享盘。
|
||
|
||
对外:
|
||
refresh(path, sheets=None) -> {"ok", "engine", "message"}
|
||
* ``PivotCaches().RefreshAll()`` 刷新所有透视缓存;
|
||
* 每个指定 sheet 的 ``PivotTables().RefreshTable()`` 兜底;
|
||
* ``CalculateFullRebuild()`` 全量重算(含数组公式),再 ``Save()``。
|
||
available() -> 是否具备 pywin32 + 可用 COM 引擎。
|
||
"""
|
||
import os
|
||
|
||
_CACHED_PROGID = None
|
||
|
||
|
||
def _import_com():
|
||
try:
|
||
import pythoncom
|
||
import win32com.client
|
||
return pythoncom, win32com.client
|
||
except ImportError:
|
||
return None, None
|
||
|
||
|
||
def available():
|
||
"""探测本机是否有 WPS 表格 / Excel COM(不发任何写操作)。"""
|
||
global _CACHED_PROGID
|
||
pythoncom, win32 = _import_com()
|
||
if pythoncom is None:
|
||
return False, '缺少 pywin32'
|
||
if _CACHED_PROGID:
|
||
return True, _CACHED_PROGID
|
||
for prog, engine in (('Ket.Application', 'WPS'), ('Excel.Application', 'Excel')):
|
||
app = None
|
||
try:
|
||
app = win32.Dispatch(prog)
|
||
_CACHED_PROGID = prog
|
||
return True, engine
|
||
except Exception:
|
||
continue
|
||
finally:
|
||
del app
|
||
return False, '未检测到 WPS 表格 / Excel COM'
|
||
|
||
|
||
def refresh(path, sheets=None, timeout_note=''):
|
||
"""刷新指定工作簿的透视缓存与公式,并保存。
|
||
|
||
Args:
|
||
path: 本地 xlsx 绝对路径
|
||
sheets: 需要兜底刷新透视表的 sheet 名列表(可选)
|
||
timeout_note: 仅用于日志说明(如「大表可能需 1-2 分钟」)
|
||
|
||
Returns:
|
||
``{"ok", "engine", "message"}``;COM 不可用时 ok=False 但不抛异常。
|
||
"""
|
||
from .. import config
|
||
|
||
path = os.path.abspath(path)
|
||
if not os.path.isfile(path):
|
||
return {'ok': False, 'engine': '', 'message': f'文件不存在:{path}'}
|
||
pythoncom, win32 = _import_com()
|
||
if pythoncom is None:
|
||
return {'ok': False, 'engine': '', 'message': '缺少 pywin32,无法刷新透视表'}
|
||
|
||
ok_engine, note = available()
|
||
if not ok_engine:
|
||
return {'ok': False, 'engine': '', 'message': note}
|
||
|
||
pythoncom.CoInitialize()
|
||
app = wb = None
|
||
engine = ''
|
||
try:
|
||
try:
|
||
app = win32.Dispatch(_CACHED_PROGID or 'Ket.Application')
|
||
engine = 'WPS' if 'Ket' in (_CACHED_PROGID or '') else 'Excel'
|
||
except Exception:
|
||
app = win32.Dispatch('Excel.Application')
|
||
engine = 'Excel'
|
||
app.DisplayAlerts = False
|
||
try:
|
||
same = [w for w in app.Workbooks
|
||
if os.path.normcase(str(getattr(w, 'FullName', '') or '')) ==
|
||
os.path.normcase(path)]
|
||
wb = same[0] if same else app.Workbooks.Open(path, UpdateLinks=2)
|
||
already_open = bool(same)
|
||
|
||
refreshed = 0
|
||
try:
|
||
for cache in wb.PivotCaches():
|
||
try:
|
||
cache.RefreshAll()
|
||
refreshed += 1
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
for name in (sheets or []):
|
||
try:
|
||
for pt in wb.Worksheets(name).PivotTables():
|
||
try:
|
||
pt.RefreshTable()
|
||
refreshed += 1
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
try:
|
||
wb.Application.CalculateFullRebuild()
|
||
except Exception:
|
||
wb.Application.CalculateFull()
|
||
wb.Save()
|
||
config.log(f'COM 刷新完成({engine}{",复用已打开工作簿" if already_open else ""}'
|
||
f',刷新透视 {refreshed} 次):{os.path.basename(path)}')
|
||
return {'ok': True, 'engine': engine,
|
||
'message': f'{engine} COM 已刷新透视/公式并保存({refreshed} 次)'}
|
||
finally:
|
||
try:
|
||
app.DisplayAlerts = True
|
||
except Exception:
|
||
pass
|
||
if wb is not None:
|
||
try:
|
||
wb.Close(SaveChanges=False)
|
||
except Exception:
|
||
pass
|
||
except Exception as e:
|
||
return {'ok': False, 'engine': engine,
|
||
'message': f'{engine or "COM"} 刷新失败:{e}' + (f'({timeout_note})' if timeout_note else '')}
|
||
finally:
|
||
if app is not None:
|
||
try:
|
||
if app.Workbooks.Count == 0:
|
||
app.Quit()
|
||
except Exception:
|
||
pass
|
||
try:
|
||
pythoncom.CoUninitialize()
|
||
except Exception:
|
||
pass
|