# -*- coding: utf-8 -*- """交易查询结果 xlsx 按商户分组拆分(金色印象定制)。 原文件含两个 sheet:sheet1(第 1 行标题、第 2 行表头、第 3 行起明细)、 汇总(第 1 行表头、第 2 行起汇总)。拆分规则: - 每个 sheet 按各自「商户名称」列过滤行,分组定义见 config.SPLIT_GROUPS; - 未命中任何分组的商户全部归入 config.SPLIT_OTHER_NAME(其他账号); - 每组生成一个新工作簿(保留原有两个 sheet 与标题行/表头行), 与原文件同目录,命名 <原文件名>_<组名>.xlsx;原全量文件保持不动。 仅复制单元格值、数字格式与列宽,不复制行高样式,导出文件为纯数据表足够使用。 """ from pathlib import Path import openpyxl from .. import config _KEY_HEADER = '商户名称' # 定位表头行的关键列名 def _norm(v): """商户名称归一化:去首尾空白 + 全角括号转半角,用于精确匹配。""" if v is None: return '' return str(v).strip().replace('(', '(').replace(')', ')') def _locate_header(ws): """在前 3 行内定位含「商户名称」的表头行号与列号;找不到返回 (None, None)。""" max_row = min(3, ws.max_row or 1) for r in range(1, max_row + 1): for c in range(1, (ws.max_column or 1) + 1): if _norm(ws.cell(r, c).value) == _KEY_HEADER: return r, c return None, None def _copy_row(ws, src_row): """把源行追加到 ws 末尾(值 + 非默认数字格式)。""" ws.append([c.value for c in src_row]) for c_new, c_src in zip(ws[ws.max_row], src_row): fmt = c_src.number_format if fmt and fmt != 'General': c_new.number_format = fmt def _copy_layout(ws_src, ws): """复制列宽,保证拆分文件可读性与原文件一致。""" for col, dim in ws_src.column_dimensions.items(): if dim.width: ws.column_dimensions[col].width = dim.width def split_trx_file(path): """按商户分组拆分交易查询 xlsx,返回新生成的工作簿路径列表。 任一环节失败由调用方兜底(原始全量文件不受影响)。 """ path = Path(path) wb = openpyxl.load_workbook(path) # ---- 预处理:每个 sheet 定位表头,并把数据行按组分桶 ---- labels = [label for label, _ in config.SPLIT_GROUPS] other = config.SPLIT_OTHER_NAME all_labels = labels + [other] group_sets = [(label, {_norm(n) for n in names}) for label, names in config.SPLIT_GROUPS] sheet_meta = {} # sheet名 -> (header_row, cus_col) 或 None(无商户列) bucket_rows = {} # (sheet名, 组名) -> [源数据行, ...] for name in wb.sheetnames: ws = wb[name] header_row, cus_col = _locate_header(ws) if not header_row: config.log(f" sheet[{name}] 未找到「{_KEY_HEADER}」列,拆分文件中该 sheet 原样保留") sheet_meta[name] = None continue sheet_meta[name] = (header_row, cus_col) for label in all_labels: bucket_rows[(name, label)] = [] for row in ws.iter_rows(min_row=header_row + 1): key = _norm(row[cus_col - 1].value) hit = other for label, names in group_sets: if key in names: hit = label break bucket_rows[(name, hit)].append(row) # ---- 逐组落盘 ---- out_paths = [] for label in all_labels: out = openpyxl.Workbook() out.remove(out.active) for name in wb.sheetnames: ws_src, ws = wb[name], out.create_sheet(name) meta = sheet_meta.get(name) if not meta: for row in ws_src.iter_rows(): _copy_row(ws, row) else: header_row, _ = meta for r in range(1, header_row): # 标题行(如 sheet1 导出时间行)原样保留 _copy_row(ws, ws_src[r]) _copy_row(ws, ws_src[header_row]) # 表头行 for row in bucket_rows[(name, label)]: _copy_row(ws, row) _copy_layout(ws_src, ws) out_path = path.with_name(f"{path.stem}_{label}{path.suffix}") out.save(out_path) detail = '、'.join( f"{name} {len(bucket_rows[(name, label)])} 行" for name in wb.sheetnames if sheet_meta.get(name) ) config.log(f" 拆分[{label}]:{detail} → {out_path}") out_paths.append(str(out_path)) return out_paths