当前位置: 首页 > news >正文

Python处理Excel文件并与数据库匹配做拼接

Python处理Excel文件并与数据库匹配做拼接

需求:Python处理Excel中数据并于数据库交互匹配得到账号信息等其他操作

Python实现

import os
import pandas as pd
import pymssql
import warnings
import time# 提取速率函数
def extract_broadband_speed(speed):if pd.notnull(speed) and 'M' in str(speed):return str(speed).split('M')[0] + 'M'else:return ''# 拼接工单标题函数
def concatenate_with_dash(row):product_type = row.get('产品类型')workorder_type = row.get('工单类型')access_type = row.get('方式')broadband_speed = row.get('速率提取')if workorder_type in ['改', '其他']:if product_type == '宽带':return f"{product_type}-{broadband_speed}-{access_type}-{workorder_type}"else:return f"{product_type}-{workorder_type}"elif product_type == '宽带':return f"{product_type}-{broadband_speed}-{access_type}-{workorder_type}机"else:return f"{product_type}-{workorder_type}机"# 清空文件夹下的所有Excel文件数据只保留一个表头数据
def clear_data_in_excel_files(current_directory):# 获取当前文件夹下的所有 Excel 文件files = [file for file in os.listdir(current_directory) if file.endswith('.xls') or file.endswith('.xlsx')]# 遍历所有 Excel 文件并清空除第一行表头外的数据for file in files:file_path = os.path.join(current_directory, file)  # 获取文件的路径df = pd.read_excel(file_path)  # 读取 Excel 文件df = df.head(0)  # 保留第一行表头df.to_excel(file_path, index=False, header=True)  # 将清空后的数据覆盖写入原 Excel 文件print(f"成功清空文件: {file}")print("成功清空所有 Excel 文件的除第一行表头外的数据")def main():start_time = time.time()print("程序开始时间:", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start_time)))warnings.filterwarnings('ignore')  # 忽略警告# 数据库连接信息server = '127.0.0.1'database = 'YD'username = 'sa'password = 'xyz@1234560'conn = pymssql.connect(server, username, password, database)# 执行 SQL 查询sql_query = '''SELECT 地市, 人员名称, [账号]FROM [ZHB]'''# 读取数据库数据data = pd.read_sql(sql_query, conn)data.rename(columns={'人员名称': '处理人'}, inplace=True)# 获取当前工作目录current_directory = os.getcwd()# 获取当前文件夹下的所有文件files = [file for file in os.listdir(current_directory) if file.endswith('.xls')]# 统计各个工单类型的总数workorder_count = {}for file in files:file_path = os.path.join(current_directory, file)  # 获取文件的路径df0 = pd.read_excel(file_path)  # 读取 Excel 文件df0['速率提取'] = df0['速率'].apply(extract_broadband_speed)df0['用户品质-NEW'] = df0['速率提取'].apply(lambda x: '千兆' if x == '1000M' else '普通品质')df0['产品工单类型合并'] = df0.apply(concatenate_with_dash, axis=1).str.replace('装机', '新装')# 修改“区域属性”列名内容,含有城市和乡镇的替换为城镇df0['区域-修改'] = df0['区域'].fillna('城镇').str.replace('城市', '城镇').str.replace('乡镇', '城镇')# 修改“是否沿街”列名中有内容的改成是,没有内容的改成否df0['是否沿街-修改'] = df0['沿街'].apply(lambda x: '是' if pd.notnull(x) else '否')df0['开始时间'] = df0['预约上门时间'].apply(lambda x: str(x).split(' ~ ')[0].strip() if isinstance(x, str) else '')df0['结束时间'] = df0['预约上门时间'].apply(lambda x: str(x).split(' ~ ')[-1].strip() if isinstance(x, str) else '')print(f"成功读取文件: {file}")# 统计各个工单类型的总数for workorder_type in df0['产品类型']:workorder_count[workorder_type] = workorder_count.get(workorder_type, 0) + 1# 使用 merge 进行数据匹配merged_df = pd.merge(df0, data[['地市', '处理人', '账号']], on=['地市', '处理人'], how='left')# 打印每个产品类型的相关信息for idx, (product_type, group_data) in enumerate(merged_df.groupby('产品类型')):print(f"产品类型 {idx + 1}: {product_type}")filtered_data = merged_df[merged_df['产品类型'].isin(['ZW', 'TR'])]filtered_data.to_excel("源文件/ZW_TR数据合并.xlsx", index=False)print("成功将产品类型为 ZW_TR数据合并.xlsx")product_types = ['云', '门铃', '喇叭', 'HM']hm_data = merged_df[merged_df['产品类型'].isin(product_types)]hm_data.to_excel("源文件/HM_数据.xlsx", index=False)# 将其它类型的数据分别保存到不同文件中other_data = merged_df[~merged_df['产品类型'].isin(['ZW', 'TR', '云', '门铃', '喇叭', 'HM'])]for product_type, group_data in other_data.groupby('产品类型'):file_name = f"源文件/{product_type}_数据.xlsx"group_data.to_excel(file_name, index=False)print(f"成功将产品类型为 {product_type} 的数据导出到文件 {file_name}")print("成功将数据库查询结果匹配并拆分业务导出为Excel文件")# 遍历目标文件夹下的所有 Excel 文件target_folder = '数据库字段/'clear_data_in_excel_files(target_folder)for file_name in os.listdir(target_folder):file_path = os.path.join(target_folder, file_name)if file_name.endswith('.xlsx'):source_file_path = os.path.join('源文件/', file_name)if os.path.isfile(source_file_path):df_source = pd.read_excel(source_file_path)df_target = pd.read_excel(file_path)for source_col, target_col in [('施工单编码', '编码'),('施工单编码', 'boss号'),('产品工单类型合并', '工单标题'),('市', '市'),('县', '县'),('接入方式', '接入方式'),('受理时间', '受理时间'),('派单时间', '派单时间'),('归档时间', '归档时间'),('预约上门时间', '前台预约时间'),('处理人', '施工人员'),# 字段添加('宽带速率', '宽带速率'),('宽带套餐资费', '套餐信息'),('开始时间', '预约上门时间'),('区域-修改', '区域'),('是否沿街-修改', '沿街商铺'),('用户品质-NEW', '品质'),]:if source_col in df_source.columns and target_col in df_target.columns:df_target[target_col] = df_source[source_col]if 'ZW_TR数据合并.xlsx' in source_file_path:if 'ZW资费' in df_source.columns and '信息' in df_target.columns:df_target['信息'] = df_source['ZW资费']df_target.to_excel(file_path, index=False)print(f"成功将字段复制到文件 {file_path} 中")# 打印工单类型的总数print("产品类型总数:")for workorder_type, count in workorder_count.items():print(f"{workorder_type}: {count}")end_time = time.time()print("程序结束时间:", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end_time)))run_time = end_time - start_timeprint("程序运行耗时:%0.2f" % run_time, "s")# 提示用户按任意键退出程序input("按任意键退出程序")if __name__ == "__main__":main()

相关文章:

  • leetcode面试经典150题——35 螺旋矩阵
  • css 输入框动态特效
  • X86汇编语言:从实模式到保护模式--命令篇
  • docker基本管理和相关概念
  • Docker网络原理及Cgroup硬件资源占用控制
  • blender 粒子系统 roughness 属性
  • 构建Servlet项目流程
  • IDEA中.java .class .jar的含义与联系
  • iptables(二)
  • Vue.delete
  • 面向对象中的单例模式
  • 智能优化算法应用:基于蚁狮算法3D无线传感器网络(WSN)覆盖优化 - 附代码
  • 一文说清google最新大模型Gemini
  • 常见位运算的公式大全(建议收藏,以防走丢)
  • 人工智能技能要求
  • (十五)java多线程之并发集合ArrayBlockingQueue
  • 【附node操作实例】redis简明入门系列—字符串类型
  • Akka系列(七):Actor持久化之Akka persistence
  • Angular 2 DI - IoC DI - 1
  • C++类的相互关联
  • Docker: 容器互访的三种方式
  • happypack两次报错的问题
  • Service Worker
  • SQL 难点解决:记录的引用
  • 闭包,sync使用细节
  • 二维平面内的碰撞检测【一】
  • 关于 Cirru Editor 存储格式
  • 聊聊directory traversal attack
  • 聊聊spring cloud的LoadBalancerAutoConfiguration
  • 让你的分享飞起来——极光推出社会化分享组件
  • 微服务入门【系列视频课程】
  • 小李飞刀:SQL题目刷起来!
  • 新手搭建网站的主要流程
  • 智能合约开发环境搭建及Hello World合约
  • Mac 上flink的安装与启动
  • 进程与线程(三)——进程/线程间通信
  • 曾刷新两项世界纪录,腾讯优图人脸检测算法 DSFD 正式开源 ...
  • #### go map 底层结构 ####
  • #LLM入门|Prompt#1.8_聊天机器人_Chatbot
  • #QT(智能家居界面-界面切换)
  • (02)vite环境变量配置
  • (11)MATLAB PCA+SVM 人脸识别
  • (12)目标检测_SSD基于pytorch搭建代码
  • (4)事件处理——(2)在页面加载的时候执行任务(Performing tasks on page load)...
  • (C#)Windows Shell 外壳编程系列4 - 上下文菜单(iContextMenu)(二)嵌入菜单和执行命令...
  • (delphi11最新学习资料) Object Pascal 学习笔记---第2章第五节(日期和时间)
  • (Forward) Music Player: From UI Proposal to Code
  • (react踩过的坑)antd 如何同时获取一个select 的value和 label值
  • (Ruby)Ubuntu12.04安装Rails环境
  • (附源码)springboot金融新闻信息服务系统 毕业设计651450
  • (每日持续更新)jdk api之FileReader基础、应用、实战
  • (三)模仿学习-Action数据的模仿
  • (转)人的集合论——移山之道
  • (转)我也是一只IT小小鸟
  • ./mysql.server: 没有那个文件或目录_Linux下安装MySQL出现“ls: /var/lib/mysql/*.pid: 没有那个文件或目录”...