Files
37duAutomation/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/report/merge_summary.py
T

89 lines
3.4 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 -*-
"""report 层 - 「物料收发汇总表」各档报表合并汇总(xq0031_xq0032 插件内模块)。
与原影刀版 merge_summary.py 同源:把同一保存目录下各档「物料收发汇总表_标签.xlsx」
合并为一个汇总文件「物料收发汇总表_<日期>.xlsx」:
- 每个报表第 4 行是表头;合并时第 4 行表头第一列新增「时间区间」字段
- 数据行第一列填入报表标签(60D / 30D / 自定义日期区间 ...)
- 跳过每表最后一行汇总行
返回汇总文件路径;无可合并报表返回 None。
"""
import re
from datetime import datetime
from pathlib import Path
import openpyxl
from .. import config
TAG = '[物料收发汇总表]'
def merge_summary(save_dir):
m = re.search(r'(\d{4}-\d{2}-\d{2})', str(save_dir))
date_tag = m.group(1) if m else datetime.now().strftime('%Y-%m-%d')
out = Path(save_dir) / f'{config.FILE_PREFIX_31}_{date_tag}.xlsx'
def _label(name):
m = re.match(rf'^{config.FILE_PREFIX_31}_(.+)\.xlsx$', name)
return m.group(1) if m else None
files = sorted(p for p in Path(save_dir).glob(f'{config.FILE_PREFIX_31}_*.xlsx')
if _label(p.name) and p.name != out.name)
if not files:
config.log(f'{TAG} 目录下没有可合并的报表: {save_dir}')
return None
header = None
all_rows, labels = [], []
for f in files:
label = _label(f.name)
try:
wb = openpyxl.load_workbook(f, data_only=True)
except Exception as e:
config.log(f'{TAG} [跳过] 无法读取的报表: {f.name}({e})')
continue
ws = wb[wb.sheetnames[0]]
h = [ws.cell(4, c).value for c in range(1, ws.max_column + 1)]
if header is None:
header = h
elif h != header:
config.log(f'{TAG} [跳过] 表头不一致: {f.name}')
continue
# 数据从第 5 行起,跳过最后一行汇总行
n = 0
for r in range(5, ws.max_row):
row = [ws.cell(r, c).value for c in range(1, ws.max_column + 1)]
if any(v is not None and str(v).strip() != '' for v in row):
all_rows.append([label] + row)
n += 1
labels.append(label)
config.log(f'{TAG} [{label}] 数据 {n} 行 <- {f.name}')
wb.close()
if not all_rows:
config.log(f'{TAG} 没有可合并的数据')
return None
if out.exists():
out.unlink()
wb = openpyxl.Workbook()
ws = wb.active
ws.title = 'Sheet1'
# 前 3 行说明,保持「表头在第 4 行」的结构与单报表一致
ws.cell(1, 1, '物料收发汇总表(汇总)')
ws.cell(2, 1, f'生成时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
ws.cell(3, 1, f'合并报表: {", ".join(labels)}')
# 第 4 行表头:第一列插入「时间区间」
ws.cell(4, 1, '时间区间')
for c, v in enumerate(header, start=2):
ws.cell(4, c, v)
# 数据(第一列为报表标签)
for r, row in enumerate(all_rows, start=5):
for c, v in enumerate(row, start=1):
ws.cell(r, c, v)
wb.save(out)
wb.close()
config.log(f'{TAG} 已生成汇总文件: {out}(共 {len(all_rows)} 条数据,{len(labels)} 个报表)')
return out