Files
37duAutomation/plugins/XQ0001-0100/XQ0085 团购数据核对/logic/sheet_xml.py
T

134 lines
5.0 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 -*-
"""xlsx 单 sheet 行级改写(zip+XML):保留透视 / 外部链接 / 其它 sheet。
订单收入明细表有 8 个透视 + 6 个外部链接,openpyxl 保存会把它们丢掉,
所以整个插件里凡是写这类工作簿都走这里:只替换目标 sheet 的 XML,
其它部件原样搬运。
对外只有 :func:`write_rows`:
``values`` = ``{行号: [第1列, 第2列, ...]}``,``formulas`` = ``{行号: [公式...]}``
(公式只从 ``config.DAILY_HELPER_FIRST`` 起写,用于 AC~AI 辅助列)。
"""
import os
import re
import zipfile
from xml.sax.saxutils import escape
from openpyxl.utils import get_column_letter as letter
from .. import config
from .paste_to_master import _CELL_RE, _ROW_RE, _col_num, _make_cell, _sheet_xml_path
from .zipio import open_zip
def _cell_styles(row_xml):
out = {}
if not row_xml:
return out
for m in _CELL_RE.finditer(row_xml):
sm = re.search(r'\bs="(\d+)"', m.group(3) or '')
if sm:
out[_col_num(m.group(1))] = sm.group(1)
return out
def _formula_cell(row_no, cnum, formula, style=''):
s_attr = f' s="{style}"' if style else ''
body = formula[1:] if formula.startswith('=') else formula
return f'<c r="{letter(cnum)}{row_no}"{s_attr}><f>{escape(body)}</f></c>'
def _build_row(row_no, values, formulas, styles, formula_from):
cells = []
for idx, value in enumerate(values or []):
if value is None or value == '':
continue
cnum = idx + 1
cells.append(_make_cell(row_no, cnum, value, styles.get(cnum, '')))
for idx, formula in enumerate(formulas or []):
if formula:
cnum = formula_from + idx
cells.append(_formula_cell(row_no, cnum, formula, styles.get(cnum, '')))
return f'<row r="{row_no}">' + ''.join(cells) + '</row>'
def patch_rows(xml_text, values, formulas, start_row, last_row, formula_from):
"""把 values/formulas 写进 sheet XML(替换 [start_row, last_row] 内的行)。"""
existing = {}
for m in _ROW_RE.finditer(xml_text):
mm = re.search(r'\br="(\d+)"', '<row' + (m.group(1) or '') + '>')
if mm:
existing[int(mm.group(1))] = m.group(0)
end = max(max(values) if values else start_row - 1, last_row or 0)
style_cache = {}
def styles_for(row_no):
if row_no in style_cache:
return style_cache[row_no]
out = {}
if row_no in existing:
out = _cell_styles(existing[row_no])
else:
for r in range(row_no - 1, max(start_row - 1, (last_row or 0) - 20), -1):
if r in existing:
out = _cell_styles(existing[r])
break
style_cache[row_no] = out
return out
pieces, pos, handled = [], 0, set()
for m in _ROW_RE.finditer(xml_text):
mm = re.search(r'\br="(\d+)"', '<row' + (m.group(1) or '') + '>')
if not mm:
continue
row_no = int(mm.group(1))
if row_no < start_row or row_no > end:
continue
pieces.append(xml_text[pos:m.start()])
pieces.append(_build_row(row_no, values.get(row_no), formulas.get(row_no),
styles_for(row_no), formula_from))
pos = m.end()
handled.add(row_no)
pieces.append(xml_text[pos:])
out = ''.join(pieces)
missing = [r for r in range(start_row, end + 1) if r not in handled]
if missing:
extra = ''.join(_build_row(r, values.get(r), formulas.get(r),
styles_for(r), formula_from) for r in missing)
out = out.replace('</sheetData>', extra + '</sheetData>', 1)
return out
def write_rows(path, sheet, values, formulas=None, start_row=None, last_row=None):
"""改写一个 sheet 的行(values 从第 1 列起;formulas 从辅助列起)。
``last_row`` 传表里原来的末行,用来把多余旧行清空。
"""
formulas = formulas or {}
if not values:
return
start_row = min(values) if start_row is None else start_row
zf = open_zip(path)
tmp = path + '.xml.tmp'
try:
xml_path = _sheet_xml_path(zf, sheet)
if not xml_path:
raise RuntimeError(f'工作簿里找不到 sheet「{sheet}」的 XML')
text = zf.read(xml_path).decode('utf-8', 'replace')
patched = patch_rows(text, values, formulas, start_row, last_row or 0,
config.DAILY_HELPER_FIRST)
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
data = patched.encode('utf-8') if info.filename == xml_path else zf.read(info)
dst.writestr(zi, data)
finally:
zf.close()
os.replace(tmp, path)