Files
37duAutomation/tests/汇总社保申报.py
puddy d1af551eac chore: 清理废弃插件与冗余文档,重构项目目录结构
1.  删除旧版xq0031_xq0032插件的冗余UI源码与配置文件
2.  迁移并标准化XQ0001-0100系列需求的插件、文档与工作流目录
3.  清理过期的需求列表、评分文档与流程底稿
4.  更新.gitignore匹配规则,适配新的目录结构
2026-09-21 16:59:05 +08:00

384 lines
14 KiB
Python
Raw Permalink 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 -*-
"""批量处理桌面"申报结果"文件夹,汇总社保缴费,结果输出到项目根目录。
流程:
1. 遍历 申报结果 下每个子文件夹(门店),找出所有"社会保险费缴费申报表*.pdf"
2. 只处理受理日期为当月的 PDF
3. 按受理日期 1-15 号为上半月、16 号及以后为下半月
4. 汇总每张 PDF 明细行的 本期应缴费额/抵缴费额/本期实际应缴纳费额(含往月补缴行)
5. 按子文件夹名匹配"账户列表.xlsx"的门店列,写入上下半月 6 列金额 + 备注
6. 结果另存到自定义文件夹"OUT_DIR"内,文件名带时间戳(不改动账户列表原文件)
"""
import os
import io
import re
import glob
import contextlib
from datetime import datetime
import camelot
import openpyxl
import pandas as pd
# ---------- 配置 ----------
ROOT_DIR = r"C:\Users\admin\Desktop\申报结果"
ACCOUNT_FILE = r"C:\Users\admin\Desktop\账户列表.xlsx"
# 结果输出目录:自定义存储文件夹(脚本运行时会自动创建)
OUT_DIR = r"D:\资料\人资\社保费用申报导出汇总\汇总结果"
PDF_KEYWORD = "社会保险费缴费申报表"
# 受理日期 1-15 号为上半月,其余为下半月
UPPER_HALF_DAY = 15
# 目标月份:默认取系统当前月份
TARGET_YEAR = datetime.now().year
TARGET_MONTH = datetime.now().month
# 汇总的三列(对应 PDF 提取出的表头名,仅用于内部求和)
AMOUNT_COLS = ["本期应缴费额", "抵缴费额", "本期实际应缴纳费额"]
# 输出到账户列表的明确列名:上半月三列 + 下半月三列
UPPER_COLS = ["上半月本期应缴费额", "上半月抵缴费额", "上半月本期实际应缴纳费额"]
LOWER_COLS = ["下半月本期应缴费额", "下半月抵缴费额", "下半月本期实际应缴纳费额"]
# ==================== PDF 提取逻辑 ====================
def clean_header(value):
"""清洗表头:去掉空格、换行符、* 等特殊字符"""
s = str(value)
s = re.sub(r"\s+", "", s) # 去所有空白:空格、换行符等
s = s.replace("*", "") # 去 * 标记
return s
def to_number(value):
"""文本型数字转数值:去千分号、内部换行/空格后尝试转 int/float,转不动保持原样"""
if value is None:
return value
s = str(value).strip()
if not s:
return value
t = re.sub(r"\s+", "", s).replace(",", "")
try:
f = float(t)
return int(f) if f.is_integer() else f
except ValueError:
return value
# 表头含这些关键词的列才转数值,避免误伤证件号等长数字文本列
NUMERIC_COL_KEYWORDS = ("人数", "工资", "基数", "费率", "费额", "金额", "序号")
def extract_accept_date(pdf_path):
"""从 PDF 最后一页提取受理日期,返回 YYYYMMDD;未找到返回 None"""
try:
import pymupdf
except ImportError:
import fitz as pymupdf
doc = pymupdf.open(pdf_path)
try:
page = doc[doc.page_count - 1]
text = page.get_text()
finally:
doc.close()
# 全角数字归一化
text = text.translate(str.maketrans("0123456789", "0123456789"))
m = re.search(r"受理日期[::]?\s*(\d{4})\D*?(\d{1,2})\D*?(\d{1,2})", text)
if not m:
return None
year, month, day = m.groups()
return "{}{:0>2}{:0>2}".format(year, month, day)
def is_total_row(row):
cells = [str(c).strip() if c is not None else "" for c in row]
if not cells:
return False
if cells[0] in ("合", "计", "合计"):
return True
if "合计" in "".join(cells[:2]):
return True
# 数据行第一列是序号(数字),即使单元格里有多个破折号也不算合计行
# (按人明细表里 人员编号/证件类型/证件号码 常为 "— —")
if cells[0].replace("*", "").replace(" ", "").isdigit():
return False
dash_count = sum(1 for c in cells if c.replace(" ", "") in ("—", "——", "-", "--"))
if dash_count >= 3:
return True
return False
def align_columns(row_list, target_n):
"""
把行调整到 target_n 列。
- 列数一致:不动
- 列数多了:针对 Camelot 把合并单元格拆成多余空列的情况,去掉特定空列
- 列数少了:补空
"""
n = len(row_list)
if n == target_n:
return row_list
if n > target_n:
# 20→17 场景:表头里索引 5 和 15 本身是空列(征收子目、抵缴费额),
# 所以保留 6 和 18,去掉 4、7、9。
if n == 20 and target_n == 17:
drop_idx = {4, 7, 9}
return [v for i, v in enumerate(row_list) if i not in drop_idx]
# 其他列数:直接截断
return row_list[:target_n]
# 少了就补空
return row_list + [None] * (target_n - n)
def extract_tables(pdf_path):
"""从单个 PDF 提取并合并明细表,返回清洗后的 DataFrame;无数据返回空 DataFrame"""
tables = camelot.read_pdf(
pdf_path,
pages="all",
flavor="lattice",
line_scale=40,
split_text=True,
)
print("共提取到 {} 个表格".format(tables.n))
all_rows = []
header = None
for i, t in enumerate(tables):
df = t.df
n_cols = len(df.columns)
print("表格 {}: {} 行, {} 列, 精度 {}%".format(
i + 1, len(df), n_cols,
t.parsing_report.get("accuracy", "?")))
# 第一张表:第一行是表头,其余为数据
if header is None:
header = [clean_header(c) for c in df.iloc[0].tolist()]
print("表头列数: {}".format(len(header)))
data_df = df.iloc[1:]
else:
data_df = df
for _, row in data_df.iterrows():
row_list = row.tolist()
if is_total_row(row_list):
print("表格 {} 检测到合计行,截断".format(i + 1))
break
# 列数对齐
row_list = align_columns(row_list, len(header))
# 全空行跳过
if all(c is None or str(c).strip() == "" for c in row_list):
continue
all_rows.append(row_list)
if not all_rows:
print("没有提取到数据行")
return pd.DataFrame()
combined = pd.DataFrame(all_rows, columns=header)
print("合并后 {} 行".format(len(combined)))
# 数值列:文本型数字转数值、去千分号
numeric_cols = [
c for c in combined.columns
if any(k in str(c) for k in NUMERIC_COL_KEYWORDS)
]
for c in numeric_cols:
combined[c] = combined[c].map(to_number)
print("数值列转换: {}".format(", ".join(numeric_cols)))
before = len(combined)
combined.drop_duplicates(inplace=True)
combined.reset_index(drop=True, inplace=True)
print("去重后 {} 行 (去除 {} 行)".format(len(combined), before - len(combined)))
return combined
# ==================== 汇总与写入逻辑 ====================
def sum_amount(df, col_name):
"""按表头名取列并求和;列不存在或值非数字按 0 计"""
if df is None or df.empty or col_name not in df.columns:
return 0.0
return float(pd.to_numeric(df[col_name], errors="coerce").fillna(0).sum())
def process_pdf(pdf_path):
"""处理单个 PDF:非当月返回 None,否则返回 (日, 应缴, 抵缴, 实缴, 是否特殊缴费, 是否医保单独申报)"""
accept = extract_accept_date(pdf_path)
if not accept:
print(" 未提取到受理日期,跳过: {}".format(os.path.basename(pdf_path)))
return None
year, month, day = int(accept[:4]), int(accept[4:6]), int(accept[6:8])
if (year, month) != (TARGET_YEAR, TARGET_MONTH):
print(" 受理 {} 非当月,跳过: {}".format(accept, os.path.basename(pdf_path)))
return None
print(" 处理 {} (受理 {})".format(os.path.basename(pdf_path), accept))
# 屏蔽 camelot 逐表刷屏日志,只保留本脚本输出
with contextlib.redirect_stdout(io.StringIO()):
df = extract_tables(pdf_path)
vals = [sum_amount(df, c) for c in AMOUNT_COLS]
cols = [str(c) for c in df.columns]
is_special = "特殊缴费类型" in cols # 按人特殊缴费明细表(含政策性补缴等)
is_medical_only = (
"抵缴费额" not in cols and "本期实际应缴纳费额" not in cols and not is_special
) # 医保单独申报短表(无抵缴/实缴两列)
return day, vals[0], vals[1], vals[2], is_special, is_medical_only
def build_remark(upper_tags, lower_tags):
"""根据上下半月标签生成备注文字"""
parts = []
if upper_tags:
parts.append("上半月:" + "+".join(sorted(upper_tags)))
if lower_tags:
parts.append("下半月:" + "+".join(sorted(lower_tags)))
if not parts:
return "日常申报"
return ";".join(parts)
def main():
print("目标月份: {}-{:02d}, 上半月截止日: {}号".format(TARGET_YEAR, TARGET_MONTH, UPPER_HALF_DAY))
print("扫描目录: {}".format(ROOT_DIR))
# 汇总结果: 子文件夹名 -> (上半月[3], 下半月[3], 上半月标签, 下半月标签)
results = {}
for folder in sorted(os.listdir(ROOT_DIR)):
folder_path = os.path.join(ROOT_DIR, folder)
if not os.path.isdir(folder_path):
continue
pdfs = sorted(glob.glob(os.path.join(folder_path, PDF_KEYWORD + "*.pdf")))
if not pdfs:
continue
upper = [0.0, 0.0, 0.0]
lower = [0.0, 0.0, 0.0]
upper_tags = set()
lower_tags = set()
had_current = False
print("== {}".format(folder))
for pdf in pdfs:
r = process_pdf(pdf)
if r is None:
continue
had_current = True
day, a1, a2, a3, is_special, is_medical_only = r
tags = set()
if is_special:
tags.add("特殊缴费")
if is_medical_only:
tags.add("医保单独申报")
if day <= UPPER_HALF_DAY:
upper[0] += a1
upper[1] += a2
upper[2] += a3
upper_tags |= tags
else:
lower[0] += a1
lower[1] += a2
lower[2] += a3
lower_tags |= tags
if had_current:
results[folder] = (upper, lower, upper_tags, lower_tags)
print("\n共 {} 个门店有当月申报".format(len(results)))
# ---------- 以账户列表为模板,写入汇总 ----------
try:
wb = openpyxl.load_workbook(ACCOUNT_FILE)
except PermissionError:
print("账户列表.xlsx 被占用,请先关闭 Excel 再运行")
return
ws = wb.active
headers = [c.value if c.value is not None else "" for c in ws[1]]
if "门店" not in headers:
print("账户列表没有'门店'列,无法写入")
return
store_col = headers.index("门店") + 1
# 上半月三列:优先新列名,兼容旧列名(本期应缴费额…)自动重命名
upper_cols = {}
for old_name, new_name in zip(AMOUNT_COLS, UPPER_COLS):
if new_name in headers:
upper_cols[new_name] = headers.index(new_name) + 1
elif old_name in headers:
idx = headers.index(old_name) + 1
ws.cell(row=1, column=idx, value=new_name)
headers[idx - 1] = new_name
upper_cols[new_name] = idx
else:
new_col = len(headers) + 1
ws.cell(row=1, column=new_col, value=new_name)
upper_cols[new_name] = new_col
headers.append(new_name)
# 下半月三列:不存在则追加
lower_cols = {}
for name in LOWER_COLS:
if name in headers:
lower_cols[name] = headers.index(name) + 1
else:
new_col = len(headers) + 1
ws.cell(row=1, column=new_col, value=name)
lower_cols[name] = new_col
headers.append(name)
# 备注列:标注医保单独申报 / 特殊缴费
remark_col = headers.index("备注") + 1 if "备注" in headers else None
if remark_col is None:
remark_col = len(headers) + 1
ws.cell(row=1, column=remark_col, value="备注")
headers.append("备注")
matched = set()
for r in range(2, ws.max_row + 1):
store = ws.cell(row=r, column=store_col).value
if not store or store not in results:
continue
upper, lower, upper_tags, lower_tags = results[store]
for name, val in zip(UPPER_COLS, upper):
ws.cell(row=r, column=upper_cols[name], value=round(val, 2))
for name, val in zip(LOWER_COLS, lower):
ws.cell(row=r, column=lower_cols[name], value=round(val, 2))
ws.cell(row=r, column=remark_col, value=build_remark(upper_tags, lower_tags))
matched.add(store)
# 直接写带时间戳的结果文件,避免覆盖/占用问题
os.makedirs(OUT_DIR, exist_ok=True)
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
save_path = os.path.join(
OUT_DIR,
"社保申报汇总_{}-{:02d}_{}.xlsx".format(TARGET_YEAR, TARGET_MONTH, stamp))
wb.save(save_path)
print("已保存: {}".format(save_path))
# ---------- 汇总报告 ----------
print("\n{:<40} {:>12} {:>12} {:>12} | {:>12} {:>12} {:>12} 备注".format(
"门店", "应缴", "抵缴", "实缴", "应缴", "抵缴", "实缴"))
for store in sorted(results):
upper, lower, upper_tags, lower_tags = results[store]
tag = "已写入" if store in matched else "!!未匹配"
print("{:<40} {:>12.2f} {:>12.2f} {:>12.2f} | {:>12.2f} {:>12.2f} {:>12.2f} {} {}".format(
store, upper[0], upper[1], upper[2], lower[0], lower[1], lower[2],
build_remark(upper_tags, lower_tags), tag))
not_written = [s for s in results if s not in matched]
if not_written:
print("\n警告:以下门店在账户列表中未找到,未写入:")
for s in not_written:
print(" - {}".format(s))
if __name__ == "__main__":
main()