feat(electron-shell): 新增插件目录选择接口并将版本升至 1.10.0

This commit is contained in:
2026-10-30 10:00:18 +08:00
parent c77a26cd99
commit 9c6e77a1f2
337 changed files with 3254 additions and 49349 deletions
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""逻辑层:核销明细增量并入「金色印象--抖音」台账。"""
@@ -0,0 +1,626 @@
# -*- coding: utf-8 -*-
"""台账增量合并:把「核销明细」里比台账更新的行追加到「金色印象--抖音」。
财务口径(2026-10 确认,参考 xq0041 新美大):
1. 台账取同目录 `抖音到账统计YYYY.M月.xlsx` 里**月份最新**的一份(排除 `_备份*`);
2. 取该 sheet「核销时间」列的**最大时间**;
3. 核销明细(可一次多份,`核销明细-核销时间-起_止.xlsx`)里比该时间旧的行剔除,
其余按**表头同名**对齐追加(明细比台账多的列忽略,台账独有的列留空);
4. 写入起点 = **真实数据末行 + 1**(max_row 被尾部空公式行撑大,直接用会在中间留空行),
尾部既有空公式行先清掉,避免与新数据交错;
5. 公式列按模板行(真实末行)下拉:A 列 `=M*1`、BT~CA 核对区
(内联公式按行号平移;共享公式 `<f t="shared" si="N"/>` 先按 si 找主定义再平移,
效果等同手工双击右下角);**CC 列业务不管,不写**。
写入方式:只改目标 sheet 的 XML(清尾部空行、`</sheetData>` 前插行、更新 dimension),
其余部件逐字节拷贝 —— 台账含 5 个透视表 + 4 个外部链接,openpyxl 全量 load→save 会丢
透视表,且目标 sheet 解压后 314MB、网表尾部还有 1.4 万行空公式行。
"""
import glob
import os
import re
import shutil
import time
import zipfile
from datetime import date, datetime
from openpyxl import load_workbook
from openpyxl.reader.strings import read_string_table
from .zipio import open_zip
from .. import config
_NS_MAIN = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
_NS_REL = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
_NS_PKGREL = '{http://schemas.openxmlformats.org/package/2006/relationships}'
_MONTH_RE = re.compile(r'(\d{4})[.\-年](\d{1,2})\s*月')
_ROW_RE = re.compile(rb'<row r="(\d+)"[^>]*?(?:/>|>(.*?)</row>)', re.S)
_CELL_RE = re.compile(rb'<c r="([A-Z]{1,3})(\d+)"([^>]*?)(?:/>|>(.*?)</c>)', re.S)
_V_RE = re.compile(rb'<v>([^<]*)</v>')
_F_RE = re.compile(rb'<f([^>]*?)(?:/>|>(.*?)</f>)', re.S)
_IS_T_RE = re.compile(rb'<t[^>]*>(.*?)</t>', re.S)
_NUM_RE = re.compile(r'-?\d+(?:\.\d+)?')
_SI_RE = re.compile(rb'si="(\d+)"')
# ==================== 通用小工具 ====================
def _to_dt(v):
if v is None:
return None
if isinstance(v, datetime):
return v
if isinstance(v, date):
return datetime(v.year, v.month, v.day)
s = str(v).strip()
if not s:
return None
for fmt in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d',
'%Y/%m/%d %H:%M:%S', '%Y/%m/%d'):
try:
return datetime.strptime(s, fmt)
except ValueError:
continue
return None
def _month_key(path):
m = _MONTH_RE.search(os.path.basename(path))
return (int(m.group(1)), int(m.group(2))) if m else (0, 0)
def _pick_latest(pattern, by_month=True):
"""排除备份文件与临时文件(`_备份20261029_145157.xlsx` 同样匹配 glob)。"""
files = [p for p in glob.glob(os.path.join(config.WORK_DIR, pattern))
if '备份' not in os.path.basename(p) and not p.endswith('.rebuild.tmp')]
if not files:
return None
if by_month:
files.sort(key=lambda p: (_month_key(p), os.path.getmtime(p)))
else:
files.sort(key=os.path.getmtime)
return files[-1]
def _col_letter(n):
s = ''
while n > 0:
n, r = divmod(n - 1, 26)
s = chr(65 + r) + s
return s
def _col_num(letters):
n = 0
for ch in letters:
n = n * 26 + (ord(ch) - 64)
return n
def _skip_cols():
return {_col_num(c) for c in config.FORMULA_SKIP_COLS}
def _xml_text(v):
return (str(v).replace('&', '&amp;').replace('<', '&lt;')
.replace('>', '&gt;').replace('"', '&quot;'))
def _num_text(v):
"""能当数字写就返回数字文本,否则 None(金额列写成数值,避免整列变文本)。"""
if v is None or isinstance(v, bool):
return None
if isinstance(v, (int, float)):
f = float(v)
else:
s = str(v).strip().replace(',', '')
if not _NUM_RE.fullmatch(s):
return None
f = float(s)
if f.is_integer() and abs(f) < 1e15:
return str(int(f))
return repr(round(f, 10))
# ==================== 台账读取(流式,不整体加载) ====================
def _sheet_xml_path(zf, sheet_name):
import xml.etree.ElementTree as ET
root = ET.fromstring(zf.read('xl/workbook.xml'))
rid = None
for s in root.iter(f'{_NS_MAIN}sheet'):
if s.get('name') == sheet_name:
rid = s.get(f'{_NS_REL}id')
break
if not rid:
return None
rels = ET.fromstring(zf.read('xl/_rels/workbook.xml.rels'))
for rel in rels.iter(f'{_NS_PKGREL}Relationship'):
if rel.get('Id') == rid:
t = (rel.get('Target') or '').lstrip('/')
return t if t.startswith('xl/') else 'xl/' + t
return None
def _cell_map(inner):
out = {}
for m in _CELL_RE.finditer(inner):
out[m.group(1)] = (m.group(3), m.group(4) or b'')
return out
def _cell_text(attrs, body, strings):
if b't="inlineStr"' in attrs:
tm = _IS_T_RE.search(body)
return tm.group(1).decode('utf-8', 'replace') if tm else None
vm = _V_RE.search(body)
if not vm:
return None
raw = vm.group(1)
if b't="s"' in attrs:
try:
idx = int(raw)
except ValueError:
return None
return strings[idx] if 0 <= idx < len(strings) else None
return raw.decode('utf-8', 'replace')
def _is_num(attrs, body):
if b't=' in attrs:
return False
return b'<v>' in body
def _scan_ledger(path, sheet_name):
"""扫台账:表头、真实末行、时间列最大值、末行模板样式、分母/分子类型。"""
zf = open_zip(path)
try:
sheet_path = _sheet_xml_path(zf, sheet_name)
if not sheet_path:
return {'ok': False, 'message': f'台账里找不到 sheet「{sheet_name}」'}
try:
strings = read_string_table(zf.open('xl/sharedStrings.xml'))
except KeyError:
strings = []
header, last_data_row = {}, config.HEADER_ROW
max_dt, max_keys = None, set()
tpl_cells, tpl_row_no = {}, 0
type_rows, shared = [], {}
with zf.open(sheet_path) as f:
buf = b''
while True:
chunk = f.read(4 << 20)
if not chunk and not buf:
break
buf += chunk
pos = 0
while True:
m = _ROW_RE.search(buf, pos)
if not m:
break
pos = m.end()
r = int(m.group(1))
inner = m.group(2) or b''
cells = _cell_map(inner)
# 共享公式主定义:只有主定义带公式文本,其余是自闭合引用
if b't="shared"' in inner:
for letter, (attrs, body) in cells.items():
fm = _F_RE.search(body)
if not fm or not fm.group(2) or b't="shared"' not in fm.group(1):
continue
sm = _SI_RE.search(fm.group(1))
if sm:
shared[sm.group(1).decode()] = (
r, fm.group(2).decode('utf-8', 'replace'))
if r == config.HEADER_ROW:
for letter, (attrs, body) in cells.items():
name = _cell_text(attrs, body, strings)
if name and str(name).strip():
header.setdefault(str(name).strip(),
_col_num(letter.decode()))
continue
if r < config.DATA_START_ROW:
continue
keys = []
for col in (b'B', b'F', b'M'):
cell = cells.get(col)
keys.append(_cell_text(cell[0], cell[1], strings) if cell else None)
if not any(k for k in keys):
continue # 尾部只剩公式的空行
last_data_row = r
tpl_cells = _tpl_from_cells(cells)
tpl_row_no = r
types = {}
for letter, (attrs, body) in cells.items():
if b'<f' in body:
continue
types[letter] = 'num' if _is_num(attrs, body) else 'text'
type_rows.append(types)
if len(type_rows) > config.NUM_TYPE_SAMPLE:
type_rows.pop(0)
dt = _to_dt(keys[2])
if dt is not None:
key = (keys[0] or '', keys[1] or '', keys[2] or '')
if max_dt is None or dt > max_dt:
max_dt, max_keys = dt, {key}
elif dt == max_dt:
max_keys.add(key)
buf = buf[pos:]
if not chunk:
break
# 数值列判定:末 N 行里数字出现次数多于文本才算(金额列写数值,其余照旧写文本)
num_cols = set()
counts = {}
for row in type_rows:
for letter, kind in row.items():
c = counts.setdefault(letter, [0, 0])
c[0 if kind == 'num' else 1] += 1
for letter, (num_cnt, txt_cnt) in counts.items():
if num_cnt > txt_cnt:
num_cols.add(_col_num(letter.decode()))
return {'ok': True, 'header': header, 'last_data_row': last_data_row,
'max_dt': max_dt, 'max_keys': max_keys, 'tpl': tpl_cells,
'tpl_row': tpl_row_no, 'num_cols': num_cols, 'shared': shared,
'max_row': _max_row(zf, sheet_path)}
finally:
zf.close()
def _max_row(zf, sheet_path):
"""dimension 里的最大行号(尾部空公式行也算)。"""
head = zf.open(sheet_path).read(4096)
m = re.search(rb'<dimension ref="[A-Z]+\d+:[A-Z]+(\d+)"', head)
return int(m.group(1)) if m else 0
def _check_formula_cols(info):
"""模板行里引用了共享公式但找不到主定义的列(找不到就没法下拉,必须报出来)。"""
bad = []
for letter, cell in (info.get('tpl') or {}).items():
if cell.get('f'):
continue
if cell.get('si') and cell['si'] not in (info.get('shared') or {}):
bad.append(letter)
return bad
def _tpl_from_cells(cells):
out = {}
for letter, (attrs, body) in cells.items():
sm = re.search(rb'\bs="(\d+)"', attrs)
info = {'s': sm.group(1).decode() if sm else None, 'f': None, 'si': None}
fm = _F_RE.search(body)
if fm:
info['f'] = fm.group(2).decode('utf-8', 'replace') if fm.group(2) else None
if b't="shared"' in fm.group(1):
si = _SI_RE.search(fm.group(1))
info['si'] = si.group(1).decode() if si else None
out[letter.decode()] = info
return out
# ==================== 公式平移 / 新行 XML ====================
def _shift_formula(formula, from_row, to_row):
"""把公式里的相对行号从 from_row 平移到 to_row($ 锁定的行号不动)。"""
if not formula or from_row == to_row:
return formula
delta = to_row - from_row
def repl(m):
col, lock, row = m.group(1), m.group(2), m.group(3)
if lock == '$':
return m.group(0)
return f'{col}{int(row) + delta}'
return re.sub(r'(?<![A-Za-z0-9_])([A-Z]{1,3})(\$?)(\d+)', repl, formula)
def _rows_xml(rows, start_row, col_map, tpl, tpl_row, shared, num_cols):
"""新行 XML:值列写值(数值列写数值、其余写文本),公式列按模板行下拉。"""
skip_cols = _skip_cols()
val_cols = {lcol for _, lcol in col_map}
parts = []
for i, row in enumerate(rows):
r = start_row + i
cells = []
for didx, lcol in col_map:
info = tpl.get(_col_letter(lcol)) or {}
s_attr = f' s="{info["s"]}"' if info.get('s') else ''
raw = row[didx] if didx < len(row) else None
if raw is None or (isinstance(raw, str) and raw == ''):
continue
letter = _col_letter(lcol)
if lcol in num_cols:
num = _num_text(raw)
if num is not None:
cells.append((lcol, f'<c r="{letter}{r}"{s_attr}><v>{num}</v></c>'))
continue
cells.append((lcol, f'<c r="{letter}{r}"{s_attr} t="inlineStr">'
f'<is><t xml:space="preserve">{_xml_text(raw)}</t></is></c>'))
for letter, info in tpl.items():
cnum = _col_num(letter)
if cnum in val_cols or cnum in skip_cols:
continue
formula = None
if info.get('f'):
formula = _shift_formula(info['f'], tpl_row, r)
elif info.get('si') and info['si'] in shared:
def_row, text = shared[info['si']]
formula = _shift_formula(text, def_row, r)
if not formula:
continue
s_attr = f' s="{info["s"]}"' if info.get('s') else ''
cells.append((cnum, f'<c r="{letter}{r}"{s_attr}><f>{formula}</f></c>'))
if not cells:
continue
cells.sort(key=lambda x: x[0])
parts.append(f'<row r="{r}">{"".join(c for _, c in cells)}</row>')
return ''.join(parts).encode('utf-8')
# ==================== 原生 XML 写入 ====================
def _append_rows_native(path, sheet_name, payload, new_max_row, skip_from_row):
"""流式重写目标 sheet:更新 dimension → 丢弃尾部空公式行 → 插新行 → 其余部件原样拷贝。"""
tmp = path + '.rebuild.tmp'
marker = b'</sheetData>'
skip_tag = f'<row r="{skip_from_row}"'.encode()
inserted = False
src = open_zip(path)
sheet_path = _sheet_xml_path(src, sheet_name)
if not sheet_path:
src.close()
raise RuntimeError(f'workbook 里找不到 sheet「{sheet_name}」')
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as dst:
for info in src.infolist():
if info.is_dir():
continue
zi = zipfile.ZipInfo(info.filename, date_time=info.date_time)
zi.compress_type = zipfile.ZIP_DEFLATED
zi.external_attr = info.external_attr
with src.open(info) as fin, dst.open(zi, 'w', force_zip64=True) as fout:
if info.filename != sheet_path:
shutil.copyfileobj(fin, fout, 4 << 20)
continue
dim_done = False
dropping = False
buf = b''
while True:
chunk = fin.read(4 << 20)
if not chunk:
if buf and not inserted:
fout.write(buf)
break
buf += chunk
if not dim_done:
buf = re.sub(
rb'(<dimension ref="[A-Z]+\d+:[A-Z]+)\d+(")',
lambda m: m.group(1) + str(new_max_row).encode() + m.group(2),
buf, count=1)
dim_done = True
if dropping:
idx = buf.find(marker)
if idx < 0:
buf = buf[-(len(marker) - 1):]
continue
fout.write(payload)
fout.write(buf[idx:])
shutil.copyfileobj(fin, fout, 4 << 20)
inserted = True
break
i_skip = buf.find(skip_tag)
i_mark = buf.find(marker)
if i_mark >= 0 and (i_skip < 0 or i_mark < i_skip):
fout.write(buf[:i_mark])
fout.write(payload)
fout.write(buf[i_mark:])
shutil.copyfileobj(fin, fout, 4 << 20)
inserted = True
break
if i_skip >= 0:
fout.write(buf[:i_skip])
buf = buf[i_skip:]
dropping = True
continue
keep = max(len(skip_tag), len(marker), 512 * 1024)
fout.write(buf[:-keep])
buf = buf[-keep:]
src.close() # Windows 下必须先放句柄,否则 os.replace 失败
if not inserted:
try:
os.remove(tmp)
except OSError:
pass
raise RuntimeError('sheet xml 里没找到 </sheetData>,未做任何修改')
os.replace(tmp, path)
return len(payload)
# ==================== 明细读取 ====================
def _header_index(header):
out = {}
for i, v in enumerate(header):
if v is None:
continue
name = str(v).strip()
if name and name not in out:
out[name] = i
return out
def _read_details(files, ledger_max, max_keys):
"""读全部核销明细,剔除比台账旧的行与台账边界已有的行。"""
head, rows = None, []
total = skip_old = skip_dup = skip_notime = 0
seen = set()
for path in files:
# 平台导出的明细 dimension 常是 A1(read_only 只会读到第一列),文件不大,直接完整加载
wb = load_workbook(path, data_only=True)
try:
ws = wb.worksheets[0]
it = ws.iter_rows(values_only=True)
first = next(it, None)
if first is None:
continue
dhead = _header_index(first)
if head is None:
head = dhead
for name in ('订单编号', config.TIME_COL):
if name not in dhead:
return {'ok': False,
'message': f'明细「{os.path.basename(path)}」缺少列「{name}」'}
ti = head[config.TIME_COL]
oi = head.get('订单编号')
ci = next((i for n, i in head.items() if n.startswith('券码')), None)
for row in it:
if row is None:
continue
total += 1
raw_t = row[ti] if ti < len(row) else None
dt = _to_dt(raw_t)
if dt is None:
skip_notime += 1
continue
if dt < ledger_max:
skip_old += 1
continue
key = (str(row[oi] or '') if oi is not None and oi < len(row) else '',
str(row[ci] or '') if ci is not None and ci < len(row) else '',
str(raw_t or ''))
if dt == ledger_max and key in max_keys:
skip_dup += 1
continue
if key in seen:
skip_dup += 1
continue
seen.add(key)
rows.append((dt, row))
finally:
wb.close()
# 多份明细按核销时间排序后追加,保持台账「时间递增」的历史形态
rows.sort(key=lambda x: x[0])
return {'ok': True, 'head': head or {}, 'rows': [r for _, r in rows],
'total': total, 'skip_old': skip_old, 'skip_dup': skip_dup,
'skip_notime': skip_notime}
# ==================== 入口 ====================
def run(dry_run=False):
"""执行合并。返回 {ok, appended, start_row, end_row, ledger, message}。"""
if not os.path.isdir(config.WORK_DIR):
return {'ok': False, 'message': f'目录不存在:{config.WORK_DIR}'}
ledger = _pick_latest(config.LEDGER_GLOB, by_month=True)
if not ledger:
return {'ok': False, 'message': f'未找到台账:{config.LEDGER_GLOB}'}
config.log(f'台账:{os.path.basename(ledger)}({_month_key(ledger)[0]}年'
f'{_month_key(ledger)[1]}月)')
details = [p for p in glob.glob(os.path.join(config.WORK_DIR, config.DETAIL_GLOB))
if '备份' not in os.path.basename(p) and not p.endswith('.rebuild.tmp')
and not os.path.basename(p).startswith('~$')]
if not details:
return {'ok': False, 'message': f'未找到核销明细:{config.DETAIL_GLOB}'}
details.sort(key=os.path.getmtime)
config.log(f'核销明细 {len(details)} 份:' +
'、'.join(os.path.basename(p) for p in details))
t0 = time.time()
info = _scan_ledger(ledger, config.LEDGER_SHEET)
if not info.get('ok'):
return {'ok': False, 'message': info.get('message')}
if config.TIME_COL not in info['header']:
return {'ok': False, 'message': f'台账表头缺少「{config.TIME_COL}」'}
if info['max_dt'] is None:
return {'ok': False, 'message': f'台账「{config.TIME_COL}」列没有有效时间'}
last_data = info['last_data_row']
tail = (info.get('max_row') or last_data) - last_data
config.log(f'台账真实末行 {last_data},{config.TIME_COL}最大 {info["max_dt"]},'
f'尾部 {tail} 行空公式行(dimension 到 {info.get("max_row")});'
f'扫描耗时 {time.time() - t0:.1f}s')
bad_formula = _check_formula_cols(info)
if bad_formula:
msg = f'模板行 {info["tpl_row"]} 的公式列 {bad_formula} 找不到共享公式主定义'
if 'A' in bad_formula:
return {'ok': False, 'message': msg + '(A 列日期为公式,无法下拉)'}
config.log(msg + ',这些列本次留空', 'WARN')
fcols = [c for c, v in info['tpl'].items() if v.get('f') or v.get('si')]
config.log(f'公式列(按模板行下拉):{fcols}', 'DEBUG')
config.log(f'不写公式的列:{list(config.FORMULA_SKIP_COLS)}(业务口径:CC 不管)', 'DEBUG')
det = _read_details(details, info['max_dt'], info['max_keys'])
if not det.get('ok'):
return {'ok': False, 'message': det.get('message')}
rows = det['rows']
config.log(f'明细共 {det["total"]} 行:保留 {len(rows)},'
f'早于台账 {det["skip_old"]},重复 {det["skip_dup"]},'
f'无核销时间 {det["skip_notime"]}')
if not rows:
return {'ok': True, 'appended': 0, 'ledger': ledger,
'message': '明细里没有比台账更新的记录'}
lhead = info['header']
dhead = det['head']
col_map = [(didx, lhead[name]) for name, didx in dhead.items()
if name in lhead and lhead[name] != 1] # A 列日期是公式,不写值
missing = [n for n in lhead if n not in dhead]
ignored = [n for n in dhead if n not in lhead]
config.log(f'列映射 {len(col_map)} 列;台账独有(留空):{missing or "无"};'
f'明细独有(忽略):{ignored or "无"}', 'DEBUG')
start_row = last_data + 1
new_max_row = start_row + len(rows) - 1
config.log(f'并入范围:台账第 {start_row} ~ {new_max_row} 行')
if dry_run:
return {'ok': True, 'appended': 0, 'start_row': start_row, 'end_row': new_max_row,
'ledger': ledger, 'message': f'[演练] 将追加 {len(rows)} 行'}
lock = os.path.join(os.path.dirname(ledger), '~$' + os.path.basename(ledger))
if os.path.exists(lock):
return {'ok': False, 'message': '台账正在 Excel 中打开(检测到 ~$ 锁文件),'
'请关闭后重跑'}
try:
with open(ledger, 'r+b'):
pass
except OSError as e:
return {'ok': False, 'message': f'台账不可写(可能被 Excel 占用):{e}'}
bak = os.path.join(
config.WORK_DIR,
f'{os.path.splitext(os.path.basename(ledger))[0]}_备份'
f'{time.strftime("%Y%m%d_%H%M%S")}.xlsx')
shutil.copy2(ledger, bak)
config.log(f'已备份 → {os.path.basename(bak)}')
payload = _rows_xml(rows, start_row, col_map, info['tpl'], info['tpl_row'],
info['shared'], info['num_cols'])
t1 = time.time()
size = _append_rows_native(ledger, config.LEDGER_SHEET, payload, new_max_row,
skip_from_row=start_row)
config.log(f'并入完成:{len(rows)} 行,耗时 {time.time() - t1:.1f}s'
f'(写入 {size / 1024:.0f} KB)')
verify = _scan_ledger(ledger, config.LEDGER_SHEET)
if verify.get('ok'):
config.log(f'校验:真实末行 {verify["last_data_row"]}(预期 {new_max_row}),'
f'{config.TIME_COL}最大 {verify["max_dt"]}')
return {'ok': True, 'appended': len(rows), 'start_row': start_row,
'end_row': new_max_row, 'ledger': ledger,
'message': f'已并入 {len(rows)} 行到台账'}
@@ -0,0 +1,335 @@
# -*- coding: utf-8 -*-
"""「抖音到账核对」按日期补共享总表取数公式(自动扫描整行同源公式)。
业务口径:该 sheet 里所有形如 `[n]资金组取数!$B$xx` 的公式都属于「同源取数」,每行应按 A 列日期
指向**当天那份**财务共享总表(当前实测 4 列 × 39 行 = 156 个):
O = [n]资金组取数!$B$24 应收岗-团购统计表-昨日遗留 (E)
P = -[n]资金组取数!$B$25 应收岗-团购统计表-本日遗留 (F)
R = [n]资金组取数!$B$22 充值
S = [n]资金组取数!$B$23
外部文件:file:///\\\\caiwu01\\共享文件夹\\1111\\TG\\{YYYY}年{M}月\\{M}.{D}\\马敏团购总表{M}.{D}.xlsx
实现:**不写死列名**——扫描目标行里每个公式,凡含 `[n]资金组取数!` 就把其中的 [n] 换成该行日期
对应的编号(前置负号、单元格地址、公式其它部分原样保留;引用别的工作簿的 [n] 不动)。
已是目标编号的单元格原样保留(含缓存值),只改对不上的。缺的外部链接新增部件并五处同步。
共享盘不可达不阻塞:公式照写,Excel 打开点「更新链接」即可取值。
"""
import os
import re
import shutil
import time
import zipfile
from datetime import date, datetime, timedelta
from openpyxl import load_workbook
from .. import config
from .zipio import open_zip
_EXTLINK_TPL = (
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
'<externalLink xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"'
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
'<externalBook r:id="rId1"><sheetNames><sheetName val="%s"/></sheetNames>'
'<sheetDataSet><sheetData sheetId="0"/></sheetDataSet></externalBook></externalLink>'
)
_EXTLINK_RELS_TPL = (
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/'
'relationships/externalLinkPath" Target="%s" TargetMode="External"/></Relationships>'
)
_CELL_RE = re.compile(r'<c r="([A-Z]+)(\d+)"([^>]*?)'
r'(?:/>|>(.*?)</c>)', re.S)
_F_RE = re.compile(r'<f([^>]*?)(?:/>|>(.*?)</f>)', re.S)
_ROW_RE = re.compile(r'<row r="(\d+)"[^>]*?(?:/>|>.*?</row>)', re.S)
# 同源引用:`[n]资金组取数!`(sheet 名不含空格,无需引号)
_EXT_REF = re.compile(r'\[(\d+)\]' + re.escape(config.LINK_SHEET) + r'!')
def _pick_ledger():
import glob
files = [p for p in glob.glob(os.path.join(config.WORK_DIR, config.LEDGER_GLOB))
if '备份' not in os.path.basename(p) and not p.endswith('.tmp')]
if not files:
return None
files.sort(key=os.path.getmtime)
return files[-1]
def _target_path(d):
return os.path.join(config.SHARE_ROOT, f'{d.year}年{d.month}月', f'{d.month}.{d.day}',
f'{config.LINK_BOOK}{d.month}.{d.day}.xlsx')
def _file_uri(path):
"""与既有 rels 一致:file:///\\\\caiwu01\\共享文件夹\\...(XML 属性里反斜杠不转义)。"""
return 'file:///' + path
def _norm_uri(uri):
"""外部链接目标归一化:去掉 file:/// 前缀、双反斜杠归一、小写(否则每次都新增重复链接)。"""
u = (uri or '').strip()
if u.lower().startswith('file:///'):
u = u[len('file:///'):]
return u.replace('\\\\', '\\').lower()
def _sheet_xml_path(zf, sheet_name):
import xml.etree.ElementTree as ET
main = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
rel = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
pkg = '{http://schemas.openxmlformats.org/package/2006/relationships}'
root = ET.fromstring(zf.read('xl/workbook.xml'))
rid = None
for s in root.iter(f'{main}sheet'):
if s.get('name') == sheet_name:
rid = s.get(f'{rel}id')
break
if not rid:
return None
rels = ET.fromstring(zf.read('xl/_rels/workbook.xml.rels'))
for r in rels.iter(f'{pkg}Relationship'):
if r.get('Id') == rid:
t = (r.get('Target') or '').lstrip('/')
return t if t.startswith('xl/') else 'xl/' + t
return None
def _parse_links(zf):
"""既有外部链接:{归一化路径: 序号} + 最大序号。"""
mapping, max_n = {}, 0
for name in zf.namelist():
m = re.match(r'xl/externalLinks/_rels/externalLink(\d+)\.xml\.rels$', name)
if not m:
continue
n = int(m.group(1))
max_n = max(max_n, n)
txt = zf.read(name).decode('utf-8', 'replace')
tm = re.search(r'Target="([^"]+)"', txt)
if tm:
mapping.setdefault(_norm_uri(tm.group(1)), n)
return mapping, max_n
def _set_row_cells(row_xml, row_no, cells):
"""用新单元格替换指定列(保留该列原有样式 s),行内其余单元格原样保留。"""
keep, styles = [], {}
for m in _CELL_RE.finditer(row_xml):
col = m.group(1)
sm = re.search(r'\bs="(\d+)"', m.group(3))
if sm:
styles.setdefault(col, sm.group(1))
if col in cells:
continue
keep.append((_col_num(col), m.group(0)))
for col, formula in cells.items():
s = styles.get(col)
s_attr = f' s="{s}"' if s else ''
keep.append((_col_num(col), f'<c r="{col}{row_no}"{s_attr}><f>{formula}</f></c>'))
keep.sort(key=lambda x: x[0])
attrs = re.match(r'<row([^>]*)>', row_xml)
head = f'<row{attrs.group(1)}>' if attrs else f'<row r="{row_no}">'
return f'{head}{"".join(c for _, c in keep)}</row>'
def _col_num(letters):
n = 0
for ch in letters:
n = n * 26 + (ord(ch) - 64)
return n
def _same_src_formulas(row_inner):
"""该行里所有引用共享总表的公式 {列: 公式文本}(共享公式引用无文本的跳过)。"""
out = {}
for c in _CELL_RE.finditer(row_inner):
body = c.group(4) or ''
fm = _F_RE.search(body)
if not fm:
continue
text = fm.group(2) or ''
if text and _EXT_REF.search(text):
out[c.group(1)] = text
return out
def _date_rows(ledger):
"""读「抖音到账核对」A 列日期 → {date: 行号}。"""
wb = load_workbook(ledger, read_only=True, data_only=False)
try:
if config.STAT_SHEET not in wb.sheetnames:
raise RuntimeError(f'台账缺少 sheet「{config.STAT_SHEET}」')
ws = wb[config.STAT_SHEET]
out = {}
for i, row in enumerate(ws.iter_rows(min_col=1, max_col=1, values_only=True), start=1):
v = row[0]
if isinstance(v, datetime):
out[v.date()] = i
elif isinstance(v, date):
out[v] = i
return out
finally:
wb.close()
def run(dry_run=False):
"""按 A 列日期给「抖音到账核对」整行同源取数公式换链接编号。"""
ledger = _pick_ledger()
if not ledger:
return {'ok': False, 'message': f'未找到台账:{config.LEDGER_GLOB}'}
config.log(f'台账:{os.path.basename(ledger)}({config.STAT_SHEET})')
try:
rows_by_date = _date_rows(ledger)
except RuntimeError as e:
return {'ok': False, 'message': str(e)}
if not rows_by_date:
return {'ok': False, 'message': f'「{config.STAT_SHEET}」A 列没有日期行'}
days = sorted(rows_by_date)
config.log(f'核对表 {len(days)} 个日期行:{days[0]} ~ {days[-1]}')
zf = open_zip(ledger)
try:
link_map, max_link = _parse_links(zf)
config.log(f'既有外部链接 {len(link_map)} 条,最大序号 {max_link}')
sheet_path = _sheet_xml_path(zf, config.STAT_SHEET)
if not sheet_path:
return {'ok': False, 'message': f'找不到「{config.STAT_SHEET}」的 xml'}
sheet_xml = zf.read(sheet_path).decode('utf-8')
wb_xml = zf.read('xl/workbook.xml').decode('utf-8')
wb_rels = zf.read('xl/_rels/workbook.xml.rels').decode('utf-8')
ct_xml = zf.read('[Content_Types].xml').decode('utf-8')
finally:
zf.close()
row_spans = {}
for m in _ROW_RE.finditer(sheet_xml):
row_spans[int(m.group(1))] = (m.start(), m.end(), m.group(0))
plan, need_new, skipped, no_formula = [], {}, 0, 0
for d in days:
row_no = rows_by_date[d]
span = row_spans.get(row_no)
if not span:
config.log(f'{d} 第 {row_no} 行 XML 未找到,跳过', 'WARN')
continue
srcs = _same_src_formulas(span[2])
if not srcs:
no_formula += 1
continue
key = _norm_uri(_target_path(d))
have = link_map.get(key)
if have is not None and all(set(_EXT_REF.findall(f)) == {str(have)}
for f in srcs.values()):
skipped += 1
continue
if have is not None:
idx, mode = have, '复用'
else:
if key not in need_new:
need_new[key] = (max_link + len(need_new) + 1, _target_path(d))
idx, mode = need_new[key][0], '新增'
todo = {}
for col, fml in srcs.items():
if set(_EXT_REF.findall(fml)) == {str(idx)}:
continue
todo[col] = _EXT_REF.sub(f'[{idx}]{config.LINK_SHEET}!', fml)
if not todo:
skipped += 1
continue
plan.append((d, row_no, idx, _target_path(d), mode, todo))
config.log(f'需更新 {len(plan)} 行(已正确 {skipped} 行、无同源公式 {no_formula} 行),'
f'新增外部链接 {len(need_new)} 条')
for d, row_no, idx, path, mode, todo in plan:
cols = ','.join(f'{c}({f})' for c, f in sorted(todo.items()))
config.log(f' {d} 第{row_no}行 → [{idx}]({mode}){cols} {path}', 'DEBUG')
if not plan:
return {'ok': True, 'rows': [], 'new_links': 0, 'ledger': ledger,
'message': f'{config.STAT_SHEET} 同源取数公式已是最新,无需改动'}
if dry_run:
return {'ok': True, 'rows': [p[1] for p in plan], 'new_links': len(need_new),
'ledger': ledger,
'message': f'[演练] 将更新 {len(plan)} 行,需新增 {len(need_new)} 条外部链接'}
if not os.path.isdir(config.SHARE_ROOT):
config.log(f'共享盘当前不可达({config.SHARE_ROOT}),公式照写,'
f'恢复到内网后打开 Excel 点「更新链接」即可取值', 'WARN')
lock = os.path.join(os.path.dirname(ledger), '~$' + os.path.basename(ledger))
if os.path.exists(lock):
return {'ok': False, 'message': '台账正在 Excel 中打开(检测到 ~$ 锁文件),请关闭后重跑'}
backup = os.path.join(
config.WORK_DIR,
f'{os.path.splitext(os.path.basename(ledger))[0]}_核对备份'
f'{time.strftime("%Y%m%d_%H%M%S")}.xlsx')
shutil.copy2(ledger, backup)
config.log(f'已备份 → {os.path.basename(backup)}')
# 按行号倒序替换,避免前面的偏移失效
spans = {}
for m in _ROW_RE.finditer(sheet_xml):
spans[int(m.group(1))] = (m.start(), m.end())
for d, row_no, idx, path, mode, todo in sorted(plan, key=lambda p: -p[1]):
s, e = spans[row_no]
row_xml = sheet_xml[s:e]
sheet_xml = sheet_xml[:s] + _set_row_cells(row_xml, row_no, todo) + sheet_xml[e:]
for key, (idx, path) in need_new.items():
rid_num = max(int(x) for x in re.findall(r'Id="rId(\d+)"', wb_rels)) + 1
rid = f'rId{rid_num}'
wb_rels = wb_rels.replace(
'</Relationships>',
f'<Relationship Id="{rid}" Type="http://schemas.openxmlformats.org/'
f'officeDocument/2006/relationships/externalLink" '
f'Target="externalLinks/externalLink{idx}.xml"/></Relationships>')
wb_xml = wb_xml.replace('</externalReferences>',
f'<externalReference r:id="{rid}"/></externalReferences>')
ct_xml = ct_xml.replace(
'</Types>',
f'<Override PartName="/xl/externalLinks/externalLink{idx}.xml" '
f'ContentType="application/vnd.openxmlformats-officedocument.'
f'spreadsheetml.externalLink+xml"/></Types>')
tmp = ledger + '.links.tmp'
replace = {
sheet_path: sheet_xml.encode('utf-8'),
'xl/workbook.xml': wb_xml.encode('utf-8'),
'xl/_rels/workbook.xml.rels': wb_rels.encode('utf-8'),
'[Content_Types].xml': ct_xml.encode('utf-8'),
}
new_files = {}
for key, (idx, path) in need_new.items():
new_files[f'xl/externalLinks/externalLink{idx}.xml'] = \
(_EXTLINK_TPL % config.LINK_SHEET).encode('utf-8')
new_files[f'xl/externalLinks/_rels/externalLink{idx}.xml.rels'] = \
(_EXTLINK_RELS_TPL % _file_uri(path)).encode('utf-8')
zf = open_zip(ledger)
try:
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as dst:
for info in zf.infolist():
if info.is_dir():
continue
zi = zipfile.ZipInfo(info.filename, date_time=info.date_time)
zi.compress_type = zipfile.ZIP_DEFLATED
zi.external_attr = info.external_attr
if info.filename in replace:
dst.writestr(zi, replace.pop(info.filename))
else:
with zf.open(info) as fin, dst.open(zi, 'w', force_zip64=True) as fout:
shutil.copyfileobj(fin, fout, 4 << 20)
for name, data in list(replace.items()) + list(new_files.items()):
dst.writestr(name, data)
finally:
zf.close()
os.replace(tmp, ledger)
config.log(f'完成:{len(plan)} 行同源公式已更新,新增外部链接 {len(need_new)} 条')
return {'ok': True, 'rows': [p[1] for p in plan], 'new_links': len(need_new),
'ledger': ledger,
'message': f'{config.STAT_SHEET} 同源取数公式已更新 {len(plan)} 行'
f'(新增外部链接 {len(need_new)} 条)'}
@@ -0,0 +1,92 @@
# -*- coding: utf-8 -*-
"""xlsx(zip) 读写的兼容层。
背景:台账被 WPS 保存后,透视缓存的 `pivotCacheRecords*.xml` 会写成
「local header 里 size=0xFFFFFFFF + ZIP64 extra 带真实大小、central directory 却缺 ZIP64 extra」。
Python 3.11 的 zipfile 从 central 取到 0xFFFFFFFF,把条目当成 4GB,
`ZipFile.open()` 直接抛 `BadZipFile: Overlapped entries ... (possible zip bomb)`。
这里在打开后把这类 ZipInfo 的 size 修成真实值(解析 local header 的 ZIP64 extra,
取不到就用下一条目偏移反推),只改内存对象、不动文件;之后 `zf.open(info)` 可正常读。
"""
import struct
import zipfile
_LFH = struct.Struct('<IHHHHHIIIHH')
def _local_sizes(fp, info):
"""从 local file header 的 ZIP64 extra 取 (usize, csize),取不到返回 (None, None)。"""
fp.seek(info.header_offset)
hdr = fp.read(30)
if len(hdr) < 30 or hdr[:4] != b'PK\x03\x04':
return None, None
nlen, elen = struct.unpack('<HH', hdr[26:30])
fp.read(nlen)
extra = fp.read(elen)
usize = csize = None
i = 0
while i + 4 <= len(extra):
hid, hlen = struct.unpack('<HH', extra[i:i + 4])
body = extra[i + 4:i + 4 + hlen]
if hid == 0x0001: # ZIP64 extended information
if len(body) >= 16:
usize, csize = struct.unpack('<QQ', body[:16])
elif len(body) >= 8:
usize = struct.unpack('<Q', body[:8])[0]
i += 4 + hlen
return usize, csize
def repair_sizes(zf):
"""修 0xFFFFFFFF 的条目大小,返回修复条数。"""
fixed = 0
fp = getattr(zf, 'fp', None)
if fp is None:
return 0
try:
if not fp.seekable():
return 0
except Exception:
return 0
try:
pos = fp.tell()
except Exception:
pos = None
for info in zf.infolist():
if info.compress_size != 0xFFFFFFFF and info.file_size != 0xFFFFFFFF:
continue
usize, csize = _local_sizes(fp, info)
if csize is None:
end = getattr(info, '_end_offset', None)
if end:
nlen = struct.unpack('<H', _peek(fp, info, 26, 2) or b'\x00\x00')[0]
elen = struct.unpack('<H', _peek(fp, info, 28, 2) or b'\x00\x00')[0]
csize = end - (info.header_offset + 30 + nlen + elen)
if csize is None:
continue
info.compress_size = csize
if usize:
info.file_size = usize
fixed += 1
if pos is not None:
try:
fp.seek(pos)
except Exception:
pass
return fixed
def _peek(fp, info, offset, size):
try:
fp.seek(info.header_offset + offset)
return fp.read(size)
except Exception:
return None
def open_zip(path):
"""open + 修复 WPS 写坏的 zip64 条目大小,返回可正常读取的 ZipFile。"""
zf = zipfile.ZipFile(path)
repair_sizes(zf)
return zf