告别手动导出:用Python脚本5分钟搞定企业微信每日考勤报表
告别手动导出用Python脚本5分钟搞定企业微信每日考勤报表每天早晨打开企业微信后台手动导出考勤报表再整理成Excel发给管理层——这个重复性工作消耗了太多时间。作为团队管理者我们真正需要的是自动化的解决方案一个能定时运行、自动生成报表并发送邮件的轻量级工具。本文将用Python实现这个需求全程无需复杂框架仅需基础编程知识。企业微信提供了完整的API接口体系我们可以通过简单的HTTP请求获取打卡原始数据。结合Python生态中强大的数据处理库整个过程就像搭积木一样简单。下面从零开始构建这个自动化系统涵盖API调用、数据清洗、报表生成和定时任务配置全流程。1. 环境准备与API权限获取在开始编写代码前需要确保具备以下条件企业微信管理员账号至少具有应用管理权限安装Python 3.6环境准备以下Python库pip install requests pandas openpyxl schedule获取API调用凭证是企业微信开发的第一步。登录企业微信管理后台在「应用管理」中找到「打卡」应用记录两个关键参数corpid企业ID在「我的企业」-「企业信息」中查看secret打卡应用的Secret在「应用管理」-「打卡」-「API」中获取注意Secret是敏感信息切勿泄露或上传到代码仓库。建议通过环境变量或配置文件管理。企业微信API采用OAuth2.0认证流程我们需要先获取access_token。这个token有效期为2小时但建议每次调用时重新获取。以下是获取token的示例代码import requests def get_access_token(corpid, secret): url fhttps://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid{corpid}corpsecret{secret} response requests.get(url).json() return response[access_token]2. 获取打卡原始数据企业微信提供了getcheckindata接口获取打卡记录支持按用户、时间范围查询。接口需要以下参数参数名类型必填说明opencheckindatatypeint是打卡类型3表示上下班打卡starttimeint是开始时间Unix时间戳endtimeint是结束时间Unix时间戳useridlistlist是用户ID列表以下是获取当天打卡数据的完整函数from datetime import datetime import time def get_checkin_data(access_token, user_ids): url fhttps://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckindata?access_token{access_token} # 计算当天0点和23:59:59的时间戳 today datetime.now().date() start_time int(time.mktime(today.timetuple())) end_time start_time 86399 # 增加23小时59分59秒 payload { opencheckindatatype: 3, starttime: start_time, endtime: end_time, useridlist: user_ids } response requests.post(url, jsonpayload).json() return response.get(checkindata, [])返回的数据包含丰富的信息如打卡时间、位置、WiFi名称等。典型的数据结构如下{ userid: zhangsan, checkin_type: 上班打卡, exception_type: 时间异常, checkin_time: 1621234567, location_title: XX大厦, wifiname: OfficeWiFi }3. 数据清洗与分析原始数据需要经过处理才能生成有意义的报表。我们使用pandas进行数据转换和分析import pandas as pd def process_checkin_data(raw_data): # 转换为DataFrame df pd.DataFrame(raw_data) # 时间戳转换 df[checkin_time] pd.to_datetime(df[checkin_time], units) # 分类上班/下班打卡 df[checkin_type] df[checkin_type].map({ 上班打卡: 上班, 下班打卡: 下班 }) # 标记异常情况 df[status] df[exception_type].apply( lambda x: 正常 if x else x ) return df迟到/缺勤分析是考勤管理的核心需求。假设公司规定9:30前打卡不算迟到def analyze_attendance(df): # 筛选上班打卡记录 morning df[df[checkin_type] 上班].copy() # 标记迟到 morning[is_late] morning[checkin_time].dt.time pd.to_datetime(09:30:00).time() # 统计结果 late_users morning[morning[is_late]][userid].unique().tolist() all_users set(df[userid].unique()) absent_users list(all_users - set(morning[userid].unique())) return { late_users: late_users, absent_users: absent_users, total_users: len(all_users) }4. 生成可视化报表数据分析结果可以通过多种形式呈现。以下是生成Excel报表的示例from openpyxl import Workbook from openpyxl.styles import Font, Alignment def generate_excel_report(analysis_result, output_path): wb Workbook() ws wb.active ws.title 考勤日报 # 设置标题 ws[A1] f考勤日报 {datetime.now().strftime(%Y-%m-%d)} ws[A1].font Font(boldTrue, size14) ws.merge_cells(A1:C1) # 写入迟到人员 ws[A3] 迟到人员 ws[A3].font Font(boldTrue) for i, user in enumerate(analysis_result[late_users], start4): ws[fA{i}] user # 写入缺勤人员 ws[B3] 缺勤人员 ws[B3].font Font(boldTrue) for i, user in enumerate(analysis_result[absent_users], start4): ws[fB{i}] user # 添加统计信息 ws[D3] 出勤率 ws[D3].font Font(boldTrue) attendance_rate 1 - len(analysis_result[absent_users])/analysis_result[total_users] ws[D4] f{attendance_rate:.1%} wb.save(output_path)更高级的可视化可以使用matplotlib生成图表import matplotlib.pyplot as plt def generate_attendance_chart(analysis_result, output_path): fig, ax plt.subplots(figsize(8, 4)) labels [正常, 迟到, 缺勤] sizes [ analysis_result[total_users] - len(analysis_result[late_users]) - len(analysis_result[absent_users]), len(analysis_result[late_users]), len(analysis_result[absent_users]) ] ax.pie(sizes, labelslabels, autopct%1.1f%%, startangle90) ax.axis(equal) # 保持圆形 plt.title(当日考勤分布) plt.savefig(output_path, dpi100, bbox_inchestight)5. 自动化部署方案实现每日自动运行有三种主流方案Windows任务计划程序配置步骤将脚本保存为attendance_report.py创建批处理文件run_report.batecho off python D:\path\to\attendance_report.py在任务计划程序中创建基本任务设置每日9:30运行Linux crontab配置# 每天9:30运行 30 9 * * * /usr/bin/python3 /path/to/attendance_report.py /var/log/attendance.log 21Python内置定时任务适合开发测试import schedule import time def daily_job(): # 这里放置主逻辑代码 print(生成考勤报表...) schedule.every().day.at(09:30).do(daily_job) while True: schedule.run_pending() time.sleep(60)6. 邮件自动发送功能最后一步是将报表自动发送给相关人员。使用Python的smtplib和email库实现import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication def send_email_with_report(report_path, chart_path, recipients): # 邮件配置 msg MIMEMultipart() msg[From] noreplycompany.com msg[To] , .join(recipients) msg[Subject] f考勤日报 {datetime.now().strftime(%Y-%m-%d)} # 邮件正文 body MIMEText(附件为当日考勤统计报表请查收。, plain) msg.attach(body) # 添加Excel附件 with open(report_path, rb) as f: part MIMEApplication(f.read(), Name考勤报表.xlsx) part[Content-Disposition] attachment; filename考勤报表.xlsx msg.attach(part) # 添加图表附件 with open(chart_path, rb) as f: part MIMEApplication(f.read(), Name考勤分布.png) part[Content-Disposition] attachment; filename考勤分布.png msg.attach(part) # 发送邮件 with smtplib.SMTP(smtp.company.com, 587) as server: server.starttls() server.login(username, password) server.send_message(msg)在实际项目中我通常会添加异常处理和日志记录功能。例如使用Python的logging模块记录运行状态import logging logging.basicConfig( filenameattendance.log, levellogging.INFO, format%(asctime)s - %(levelname)s - %(message)s ) try: # 主逻辑代码 logging.info(开始生成考勤报表) except Exception as e: logging.error(f生成报表失败: {str(e)}) send_error_notification(str(e))这套系统在30人团队中运行半年后平均每周为HR节省4小时手工操作时间。最实用的改进是添加了异常打卡提醒功能——当检测到员工在非公司常用位置打卡时自动发送预警邮件给直属主管。