Files
37duAutomation/plugins/xq0041/logic/stat_links.py
T

283 lines
12 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 -*-
"""「新美大核对统计」按日期补 V/W 列外部链接公式。
业务口径(从台账既有 62 条链接反推):
V = =[N]资金组取数!$B$5 (应收岗-团购统计表-昨日遗留)
W = =[N]资金组取数!$B$6 (应收岗-团购统计表-本日遗留)
外部文件:file:///\\\\caiwu01\\共享文件夹\\1111\\TG\\{YYYY}年{M}月\\{M}.{D}\\马敏团购总表{M}.{D}.xlsx
实现:能复用的链接按 target 匹配复用,缺的新增 externalLinkNN.xml + rels +
workbook.xml 的 externalReferences + workbook.xml.rels + Content_Types 声明;
目标 sheet 只改对应行的 V/W 单元格,其余部件原样拷贝。
"""
import os
import re
import shutil
import time
import zipfile
from datetime import date, datetime, timedelta
from openpyxl import load_workbook
from .. import config
_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+)"([^>]*?)(?:/>|>(.*?)</c>)', re.S)
def _pick_latest(pattern):
import glob
files = [p for p in glob.glob(os.path.join(config.WORK_DIR, pattern))
if '备份' not in os.path.basename(p)]
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 _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 _col_num(letters):
n = 0
for ch in letters:
n = n * 26 + (ord(ch) - 64)
return n
def _set_row_cells(row_xml, row_no, cells):
keep = []
style_default = None
for m in _CELL_RE.finditer(row_xml):
col = m.group(1)
sm = re.search(r'\bs="(\d+)"', m.group(3))
if style_default is None and sm:
style_default = sm.group(1)
if col in cells:
continue
keep.append((_col_num(col), m.group(0)))
for col, (formula, style) in cells.items():
s = style or style_default
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 _norm_uri(uri):
"""外部链接目标归一化:`file:///\\\\caiwu01\\共享...` → `\\\\caiwu01\\共享...`(小写)。
比对方是本地路径,不带 file:/// 前缀;不归一会永远匹配不上,
导致每次运行都新增一条重复的外部链接。
"""
u = (uri or '').strip()
if u.lower().startswith('file:///'):
u = u[len('file:///'):]
return u.replace('\\\\', '\\').lower()
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 run(d_from=None, d_to=None, dry_run=False):
"""按日期区间补 V/W。d_from/d_to 为空则取最新「团购收益明细_YYYYMMDD_YYYYMMDD.xlsx」的日期。"""
ledger = _pick_latest(config.LEDGER_GLOB)
if not ledger:
return {'ok': False, 'message': f'未找到台账:{config.LEDGER_GLOB}'}
config.log(f'台账:{os.path.basename(ledger)}')
if not d_from:
detail = _pick_latest(config.DETAIL_GLOB)
if detail:
m = re.search(r'(\d{8})_(\d{8})', os.path.basename(detail)) or \
re.search(r'(\d{8})', os.path.basename(detail))
if m:
d_from = m.group(1)
d_to = m.group(2) if m.lastindex and m.lastindex >= 2 else m.group(1)
if not d_from:
today = date.today()
d_from = (today - timedelta(days=1)).isoformat()
d_to = today.isoformat()
d1 = datetime.strptime(d_from.replace('-', '')[:8], '%Y%m%d').date()
d2 = datetime.strptime(str(d_to).replace('-', '')[:8], '%Y%m%d').date()
config.log(f'日期区间:{d1} ~ {d2}')
wb = load_workbook(ledger, read_only=True, data_only=False)
if config.STAT_SHEET not in wb.sheetnames:
wb.close()
return {'ok': False, 'message': f'台账缺少 sheet「{config.STAT_SHEET}」'}
ws = wb[config.STAT_SHEET]
date_rows = {}
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):
date_rows[v.date()] = i
elif isinstance(v, date):
date_rows[v] = i
wb.close()
days, day = [], d1
while day <= d2:
days.append(day)
day += timedelta(days=1)
skipped = [d for d in days if d not in date_rows]
if skipped:
config.log(f'核对统计表里没有这些日期行,跳过:{[str(d) for d in skipped]}', 'WARN')
days = [d for d in days if d in date_rows]
if not days:
return {'ok': False, 'message': '没有可处理的日期行'}
zf = zipfile.ZipFile(ledger)
link_map, max_link = _parse_links(zf)
config.log(f'既有外部链接 {len(link_map)} 条,最大序号 {max_link}')
plan, need_new = [], []
for d in days:
path = _target_path(d)
if _norm_uri(path) in link_map:
plan.append((d, date_rows[d], link_map[_norm_uri(path)], path, '复用'))
else:
idx = max_link + len(need_new) + 1
need_new.append((idx, path, _file_uri(path)))
plan.append((d, date_rows[d], idx, path, '新增'))
for d, row_no, idx, path, mode in plan:
config.log(f' {d} → 第{row_no}行 [{idx}]({mode}){path}')
if dry_run:
zf.close()
return {'ok': True, 'rows': [p[1] for p in plan],
'message': f'[演练] {len(plan)} 行将更新 V/W,需新增 {len(need_new)} 条外部链接'}
if not os.path.isdir(config.SHARE_ROOT):
config.log(f'共享盘当前不可达({config.SHARE_ROOT}),公式照写,'
f'恢复后打开 Excel 点「更新链接」即可取值', 'WARN')
sheet_path = _sheet_xml_path(zf, config.STAT_SHEET)
if not sheet_path:
zf.close()
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')
for d, row_no, idx, path, mode in plan:
m = re.search(r'<row r="' + str(row_no) + r'"[^>]*>.*?</row>', sheet_xml, re.S)
if not m:
config.log(f'第 {row_no} 行 XML 未找到,跳过', 'WARN')
continue
# 注意:XML 的 <f> 里放公式正文,不带 Excel 界面上的前导 '='
new_row = _set_row_cells(m.group(0), row_no, {
'V': (f'[{idx}]{config.LINK_SHEET}!$B$5', None),
'W': (f'[{idx}]{config.LINK_SHEET}!$B$6', None),
})
sheet_xml = sheet_xml[:m.start()] + new_row + sheet_xml[m.end():]
config.log(f'{d} 行已补上团购统计表取数链接')
for idx, path, uri in need_new:
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 + '.rebuild.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 idx, path, uri in need_new:
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 % uri).encode('utf-8')
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)
zf.close()
os.replace(tmp, ledger)
config.log(f'完成:{len(plan)} 行更新 V/W,新增外部链接 {len(need_new)} 条')
return {'ok': True, 'rows': [p[1] for p in plan], 'new_links': len(need_new),
'message': f'核对统计 V/W 已更新 {len(plan)} 行'}