2026/4/17 19:48:57
网站建设
项目流程
网站会说话,兄弟们给个能用的网站,网站优化建设河南,网站建设与实践免费python编程教程#xff1a;https://pan.quark.cn/s/2c17aed36b72引言#xff1a;为什么需要员工管理系统#xff1f;想象你是一家快速成长的科技公司HR#xff0c;每天要处理数十份员工入职、离职、调岗申请#xff0c;管理数百名员工的薪资、考勤和绩效数据。用Excel…免费python编程教程https://pan.quark.cn/s/2c17aed36b72引言为什么需要员工管理系统想象你是一家快速成长的科技公司HR每天要处理数十份员工入职、离职、调岗申请管理数百名员工的薪资、考勤和绩效数据。用Excel表格记录数据容易错乱且难以共享。纸质档案查找效率低下且容易丢失。这时一个电子化的员工管理系统就显得尤为重要。Python凭借其简洁的语法和丰富的库支持成为开发中小型管理系统的理想选择。本文将带你从零开始构建一个完整的员工管理系统涵盖员工信息管理、薪资计算、考勤记录等核心功能并提供Web界面和命令行两种交互方式。一、系统设计先画蓝图再施工1. 功能模块规划一个完整的员工管理系统通常包含员工信息管理增删改查员工基本信息薪资管理计算月工资、生成薪资单考勤管理记录上下班时间、计算加班时长部门管理维护公司组织架构报表生成导出员工花名册、薪资汇总表2. 数据存储方案小型系统使用SQLite数据库无需安装文件存储中型系统MySQL/PostgreSQL支持多用户并发快速原型JSON文件适合学习演示本文选择SQLite作为存储方案兼顾易用性和扩展性。3. 用户界面选择命令行界面(CLI)适合开发初期快速验证功能Web界面提供更友好的用户体验桌面GUI使用PyQt/Tkinter适合本地部署我们将先实现CLI版本再扩展为Web应用。二、基础实现命令行版员工管理系统1. 环境准备# 安装所需库 # pip install tabulate flask # Web版本需要额外安装flask2. 数据库设计import sqlite3 from sqlite3 import Error def create_connection(db_file): 创建数据库连接 conn None try: conn sqlite3.connect(db_file) print(f成功连接到SQLite数据库版本: {sqlite3.version}) return conn except Error as e: print(e) return conn def create_tables(conn): 创建数据表 try: sql_create_employees_table CREATE TABLE IF NOT EXISTS employees ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, gender TEXT, birth_date TEXT, department TEXT, position TEXT, hire_date TEXT, salary REAL, phone TEXT, email TEXT ); sql_create_attendance_table CREATE TABLE IF NOT EXISTS attendance ( id INTEGER PRIMARY KEY AUTOINCREMENT, employee_id INTEGER, date TEXT, check_in TEXT, check_out TEXT, overtime_hours REAL, FOREIGN KEY (employee_id) REFERENCES employees (id) ); conn.execute(sql_create_employees_table) conn.execute(sql_create_attendance_table) print(数据表创建成功) except Error as e: print(e) # 初始化数据库 conn create_connection(employee_management.db) if conn is not None: create_tables(conn) conn.close()3. 核心功能实现员工信息管理def add_employee(conn, employee): 添加新员工 sql INSERT INTO employees(name, gender, birth_date, department, position, hire_date, salary, phone, email) VALUES(?,?,?,?,?,?,?,?,?) cur conn.cursor() cur.execute(sql, employee) conn.commit() return cur.lastrowid def get_all_employees(conn): 获取所有员工 cur conn.cursor() cur.execute(SELECT * FROM employees) rows cur.fetchall() return rows def update_employee(conn, employee_id, updated_data): 更新员工信息 columns , .join([f{key} ? for key in updated_data.keys()]) values list(updated_data.values()) values.append(employee_id) sql fUPDATE employees SET {columns} WHERE id ? cur conn.cursor() cur.execute(sql, values) conn.commit() return cur.rowcount def delete_employee(conn, employee_id): 删除员工 sql DELETE FROM employees WHERE id? cur conn.cursor() cur.execute(sql, (employee_id,)) conn.commit() return cur.rowcount薪资计算def calculate_salary(conn, employee_id, month): 计算月工资 # 获取员工基本信息 cur conn.cursor() cur.execute(SELECT salary, department FROM employees WHERE id?, (employee_id,)) employee cur.fetchone() if not employee: return None base_salary, department employee # 获取当月考勤记录 cur.execute( SELECT SUM(overtime_hours) FROM attendance WHERE employee_id? AND strftime(%Y-%m, date)? , (employee_id, month)) overtime cur.fetchone()[0] or 0 # 简单薪资计算规则可根据部门调整 overtime_pay overtime * (base_salary / 21.75 / 8 * 1.5) # 1.5倍加班费 # 部门补贴示例 dept_bonus { 技术部: 1000, 市场部: 800, 人事部: 500 }.get(department, 0) total_salary base_salary overtime_pay dept_bonus return { base_salary: base_salary, overtime_pay: overtime_pay, dept_bonus: dept_bonus, total_salary: total_salary }考勤管理def record_attendance(conn, employee_id, date, check_in, check_out): 记录考勤 # 计算工作时长简化版 from datetime import datetime try: in_time datetime.strptime(check_in, %H:%M) out_time datetime.strptime(check_out, %H:%M) work_hours (out_time - in_time).total_seconds() / 3600 # 超过8小时算加班简化计算 overtime max(0, work_hours - 8) sql INSERT INTO attendance(employee_id, date, check_in, check_out, overtime_hours) VALUES(?,?,?,?,?) cur conn.cursor() cur.execute(sql, (employee_id, date, check_in, check_out, overtime)) conn.commit() return cur.lastrowid except ValueError: print(时间格式错误请使用HH:MM格式) return None4. 命令行交互界面from tabulate import tabulate def print_menu(): 打印菜单 print(\n 员工管理系统 ) print(1. 添加员工) print(2. 查看所有员工) print(3. 更新员工信息) print(4. 删除员工) print(5. 记录考勤) print(6. 计算薪资) print(7. 退出系统) def main(): conn create_connection(employee_management.db) if conn is None: print(无法连接数据库) return while True: print_menu() choice input(请选择操作: ) if choice 1: # 添加员工 print(\n添加新员工) name input(姓名: ) gender input(性别: ) birth_date input(出生日期(YYYY-MM-DD): ) department input(部门: ) position input(职位: ) hire_date input(入职日期(YYYY-MM-DD): ) salary float(input(基本工资: )) phone input(电话: ) email input(邮箱: ) employee (name, gender, birth_date, department, position, hire_date, salary, phone, email) employee_id add_employee(conn, employee) print(f员工添加成功ID: {employee_id}) elif choice 2: # 查看所有员工 employees get_all_employees(conn) if employees: headers [ID, 姓名, 性别, 出生日期, 部门, 职位, 入职日期, 基本工资, 电话, 邮箱] print(tabulate(employees, headersheaders, tablefmtgrid)) else: print(没有员工记录) elif choice 3: # 更新员工信息 employee_id int(input(输入要更新的员工ID: )) field input(输入要更新的字段(name/gender/department/salary等): ) value input(f输入新的{field}值: ) # 根据字段类型转换 if field in [salary, id]: value float(value) if . in value else int(value) updated update_employee(conn, employee_id, {field: value}) if updated: print(更新成功) else: print(未找到该员工或更新失败) elif choice 4: # 删除员工 employee_id int(input(输入要删除的员工ID: )) if delete_employee(conn, employee_id): print(删除成功) else: print(删除失败未找到该员工) elif choice 5: # 记录考勤 employee_id int(input(员工ID: )) date input(日期(YYYY-MM-DD): ) check_in input(签到时间(HH:MM): ) check_out input(签退时间(HH:MM): ) if record_attendance(conn, employee_id, date, check_in, check_out): print(考勤记录成功) else: print(考勤记录失败) elif choice 6: # 计算薪资 employee_id int(input(员工ID: )) month input(计算月份(YYYY-MM): ) salary_info calculate_salary(conn, employee_id, month) if salary_info: print(\n薪资明细:) for k, v in salary_info.items(): print(f{k.replace(_, ).title()}: {v:.2f}) else: print(未找到该员工或计算失败) elif choice 7: print(退出系统) break else: print(无效选择请重新输入) conn.close() if __name__ __main__: main()三、系统升级Web版员工管理系统1. 使用Flask构建Web界面from flask import Flask, render_template, request, redirect, url_for app Flask(__name__) # 数据库连接函数同上 def get_db_connection(): conn sqlite3.connect(employee_management.db) conn.row_factory sqlite3.Row # 使查询结果以字典形式返回 return conn app.route(/) def index(): conn get_db_connection() employees conn.execute(SELECT * FROM employees).fetchall() conn.close() return render_template(index.html, employeesemployees) app.route(/employee/add, methods[GET, POST]) def add_employee_web(): if request.method POST: # 获取表单数据 name request.form[name] department request.form[department] salary float(request.form[salary]) conn get_db_connection() employee_id add_employee(conn, (name, None, None, department, None, None, salary, None, None)) conn.close() return redirect(url_for(index)) return render_template(add_employee.html) # 其他路由处理更新、删除等类似实现2. HTML模板示例templates/index.html!DOCTYPE html html head title员工管理系统/title style table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } /style /head body h1员工列表/h1 a href/employee/add添加新员工/a table tr thID/th th姓名/th th部门/th th基本工资/th th操作/th /tr {% for employee in employees %} tr td{{ employee[id] }}/td td{{ employee[name] }}/td td{{ employee[department] }}/td td{{ employee[salary] }}/td td a href/employee/edit/{{ employee[id] }}编辑/a a href/employee/delete/{{ employee[id] }}删除/a /td /tr {% endfor %} /table /body /html3. 运行Web应用if __name__ __main__: app.run(debugTrue)四、系统优化建议1. 安全性增强添加用户认证使用Flask-Login对敏感操作添加权限控制使用参数化查询防止SQL注入2. 功能扩展添加员工照片上传功能实现多条件搜索按部门、职位等筛选添加数据导入导出功能Excel/CSV3. 性能优化对频繁查询添加数据库索引实现数据分页显示使用缓存机制存储常用查询结果4. 部署方案开发环境Flask内置服务器生产环境Gunicorn Nginx云部署AWS/Azure/阿里云等云服务五、常见问题解决方案1. 数据库连接失败检查数据库文件路径是否正确确保有写入权限验证SQLite版本兼容性2. 中文显示乱码在连接数据库时添加detect_typessqlite3.PARSE_DECLTYPES参数确保HTML模板设置正确的字符编码UTF-83. Web界面样式问题引入Bootstrap等CSS框架快速美化界面使用Flask-WTF处理表单样式4. 数据一致性错误在关键操作中添加事务处理实现数据验证逻辑如邮箱格式、薪资非负等结语从基础到进阶的系统开发路径通过本文的实现你已经掌握了一个完整员工管理系统的开发流程从命令行原型到Web应用从基础CRUD到业务逻辑实现。这个系统可以根据实际需求进一步扩展小型团队使用命令行版本足够满足需求中小企业部署Web版本提供多人协作大型企业在现有架构上添加更多模块招聘、培训等Python的灵活性使得这样的系统可以轻松集成其他服务比如通过API与考勤机对接或与财务系统同步薪资数据。随着实践经验的积累你可以逐步将这个基础系统演变为企业级的人力资源管理平台。