# -*- coding: utf-8 -*- """通联扫码统计:把导出的「支付数据」追加到工作簿「支付数据」sheet(累计粘贴)。 导出文件 D:\\资料\\财务\\通联数据导出核对\\支付数据-20261109.xlsx sheet「支付数据」,第 1 行标题,A..BK 共 63 列 目标文件 D:\\资料\\财务\\通联数据导出核对\\扫码统计11.9.xlsx sheet「支付数据」,第 1 行标题=导出标题前多一列 A「日期」(公式 =IF(HOUR(G)<10,INT(G)-1,INT(G))), 即导出 A..BK 对应目标 B..BK。追加时从目标最后一个数据行的下一行起,把导出数据写入 B 列起, A 列沿用目标表已有日期公式。先校验标题逐列对齐,再整块复制粘贴,最后抽样校验首/中/末行。 引擎:WPS/Excel COM(Ket.Application → et.Application → Excel.Application)。 """ import os import sys import time # ---------- 配置(全部固化在文件内,不接受命令行参数) ---------- TARGET_WORKBOOK = r"D:\资料\财务\通联数据导出核对\扫码统计11.9.xlsx" SOURCE_WORKBOOK = r"D:\资料\财务\通联数据导出核对\支付数据-20261109.xlsx" SHEET_NAME = "支付数据" TITLE_ROWS = 1 # 导出表标题行数,追加时跳过 TGT_COL_OFFSET = 1 # 目标表在导出列前多 1 列(A 列「日期」) DATE_COL = 1 # 目标表日期列(公式列) COM_PROG_IDS = ("Ket.Application", "et.Application", "Excel.Application") XL_UP = -4162 # xlUp XL_PASTE_ALL = -4104 # xlPasteAll class FlowError(RuntimeError): """流程执行失败(文件不存在 / COM 不可用 / 标题不一致等)。""" def log(msg, *args): print("[{}] {}".format(time.strftime("%H:%M:%S"), msg % args if args else msg)) def open_app(): import pythoncom import win32com.client pythoncom.CoInitialize() app, prog_id, last_err = None, "", None for pid in COM_PROG_IDS: try: app = win32com.client.Dispatch(pid) prog_id = pid break except Exception as e: # noqa: BLE001 - COM 探测失败逐个兜底 last_err = e if app is None: pythoncom.CoUninitialize() raise FlowError("本机未检测到可用的 WPS/Excel COM(依次尝试 {} 均失败):{}".format( " / ".join(COM_PROG_IDS), last_err)) app.DisplayAlerts = False return app, prog_id def open_workbook(app, path): """已打开则复用(不关闭、不影响用户实例),否则自行打开。返回 (workbook, 是否复用)。""" if not os.path.isfile(path): raise FlowError("文件不存在:{}".format(path)) abs_path = os.path.normcase(os.path.abspath(path)) for w in app.Workbooks: try: if os.path.normcase(os.path.abspath(str(w.FullName or ""))) == abs_path: return w, True except Exception: # noqa: BLE001 continue return app.Workbooks.Open(path), False def read_row(ws, row, first_col, last_col): vals = ws.Range(ws.Cells(row, first_col), ws.Cells(row, last_col)).Value2 if not isinstance(vals, tuple): return (vals,) if vals and not isinstance(vals[0], tuple): return vals return vals[0] def _same(a, b): if a is None and b is None: return True if a is None or b is None: return False if isinstance(a, (int, float)) and isinstance(b, (int, float)) \ and not isinstance(a, bool) and not isinstance(b, bool): return abs(float(a) - float(b)) <= 1e-4 return str(a).strip() == str(b).strip() def check_headers(ws_src, ws_tgt, cols): """校验目标表第 2 列起与导出表标题逐列一致,避免错列追加。""" src_header = read_row(ws_src, 1, 1, cols) tgt_header = read_row(ws_tgt, 1, 1 + TGT_COL_OFFSET, cols + TGT_COL_OFFSET) diffs = [(c + 1, v_s, v_t) for c, (v_s, v_t) in enumerate(zip(src_header, tgt_header)) if not _same(v_s, v_t)] if diffs: raise FlowError("标题行不一致,已中止追加(导出列号, 导出, 目标):{}".format(diffs[:8])) log("标题校验通过:导出 A..%s(%d 列)= 目标 B..%s", _col_letter(cols), cols, _col_letter(cols + TGT_COL_OFFSET)) def main(): import pythoncom app, prog_id = open_app() log("COM 引擎:%s", prog_id) wb_tgt = wb_src = None tgt_opened = src_opened = False try: wb_src, src_reused = open_workbook(app, SOURCE_WORKBOOK) src_opened = not src_reused wb_tgt, tgt_reused = open_workbook(app, TARGET_WORKBOOK) tgt_opened = not tgt_reused if wb_tgt.ReadOnly: raise FlowError("目标工作簿以只读方式打开,无法追加:{}".format(TARGET_WORKBOOK)) log("导出表:%s%s", SOURCE_WORKBOOK, "(复用已打开)" if src_reused else "") log("目标簿:%s%s", TARGET_WORKBOOK, "(复用已打开)" if tgt_reused else "") ws_src = wb_src.Worksheets(SHEET_NAME) ws_tgt = wb_tgt.Worksheets(SHEET_NAME) src_last = ws_src.Cells(ws_src.Rows.Count, 1).End(XL_UP).Row cols = ws_src.UsedRange.Column + ws_src.UsedRange.Columns.Count - 1 if src_last <= TITLE_ROWS: raise FlowError("导出表「{}」没有数据行(最后一行 {})".format(SHEET_NAME, src_last)) check_headers(ws_src, ws_tgt, cols) try: if ws_tgt.AutoFilterMode: ws_tgt.AutoFilterMode = False log("已取消目标表筛选(追加前)") except Exception: # noqa: BLE001 pass # 目标表最后一个数据行按 B 列(订单id)判定:A 列日期公式已预填到几十万行,不能看 A 列 tgt_last = ws_tgt.Cells(ws_tgt.Rows.Count, 1 + TGT_COL_OFFSET).End(XL_UP).Row dst_row = tgt_last + 1 rows = src_last - TITLE_ROWS log("导出 %d 行数据(A%d:%s%d),目标数据末行 %d,追加到第 %d 行起(%s 列)", rows, TITLE_ROWS + 1, _col_letter(cols), src_last, tgt_last, dst_row, _col_letter(1 + TGT_COL_OFFSET)) rng = ws_src.Range(ws_src.Cells(TITLE_ROWS + 1, 1), ws_src.Cells(src_last, cols)) rng.Copy() try: ws_tgt.Cells(dst_row, 1 + TGT_COL_OFFSET).PasteSpecial(Paste=XL_PASTE_ALL) finally: try: app.CutCopyMode = False except Exception: # noqa: BLE001 pass new_last = dst_row + rows - 1 actual_new_last = ws_tgt.Cells(ws_tgt.Rows.Count, 1 + TGT_COL_OFFSET).End(XL_UP).Row if actual_new_last != new_last: raise FlowError("追加后行号异常:预期最后一行 {},实际 {}".format(new_last, actual_new_last)) log("已追加完成:目标「%s」数据行 %d → %d", SHEET_NAME, tgt_last, actual_new_last) # A 列日期公式:模板已预填;若最后两行缺失则从上一行填充并重算新增段 if not str(ws_tgt.Cells(new_last, DATE_COL).Formula).startswith("="): ws_tgt.Range(ws_tgt.Cells(dst_row - 1, DATE_COL), ws_tgt.Cells(new_last, DATE_COL)).FillDown() log("A 列日期公式缺失,已从第 %d 行向下填充", dst_row - 1) ws_tgt.Range(ws_tgt.Cells(dst_row, DATE_COL), ws_tgt.Cells(new_last, DATE_COL)).Calculate() wb_tgt.Save() log("目标工作簿已保存") # 抽样校验:首/中/末行,数据列逐格 + A 列日期口径 for tag, src_row in (("首行", TITLE_ROWS + 1), ("中间行", TITLE_ROWS + 1 + rows // 2), ("末行", src_last)): tgt_row = dst_row + (src_row - TITLE_ROWS - 1) diffs = [(c + 1, v_s, v_t) for c, (v_s, v_t) in enumerate(zip(read_row(ws_src, src_row, 1, cols), read_row(ws_tgt, tgt_row, 1 + TGT_COL_OFFSET, cols + TGT_COL_OFFSET))) if not _same(v_s, v_t)] if diffs: raise FlowError("抽样校验失败({},第 {} 行):{}".format(tag, tgt_row, diffs[:8])) pay_time = ws_tgt.Cells(tgt_row, 1 + TGT_COL_OFFSET + 5).Value2 # G 列支付完成时间 expect_date = int(pay_time) - 1 if int(pay_time * 24) % 24 < 10 else int(pay_time) actual_date = ws_tgt.Cells(tgt_row, DATE_COL).Value2 if not _same(float(expect_date), actual_date): raise FlowError("A 列日期校验失败(第 {} 行):预期 {} 实际 {}".format( tgt_row, expect_date, actual_date)) log("抽样校验通过(%s,第 %d 行,日期值 %s)", tag, tgt_row, actual_date) finally: try: if wb_tgt is not None and tgt_opened: wb_tgt.Close(SaveChanges=False) except Exception: # noqa: BLE001 pass try: if wb_src is not None and src_opened: wb_src.Close(SaveChanges=False) except Exception: # noqa: BLE001 pass try: app.DisplayAlerts = True if app.Workbooks.Count == 0: app.Quit() except Exception: # noqa: BLE001 pass try: pythoncom.CoUninitialize() except Exception: # noqa: BLE001 pass log("流程通过") return 0 def _col_letter(col): """列号转字母(63 → BK)。""" s = "" while col > 0: col, rem = divmod(col - 1, 26) s = chr(65 + rem) + s return s if __name__ == "__main__": try: sys.exit(main()) except FlowError as e: print("[ERROR] {}".format(e)) sys.exit(2)