python excel 批量更换表头函数

最近几天忙朋友信息化,他拿来了几十个excel,每个excel里又包含 多个sheet,名字不统一,向数据库中导入时,时时错误

如有的头写成了”联系人”,有的是”姓名”,有的是”相关负责人”等等,手工导出几个后,

看看想完成没几天难呀,就加班做了个工具,同类的表统一更换成指定表头

但有的excel,有的十列,有的13列,有的20列,好头疼,调试后又增加,扩列功能,如不到19列的,增加空

有用的朋友可以借签 ,用时如有什么弄不成的,随时交流

-*- coding: utf-8 -*-
import base64
import pandas as pd
from pandas.core.frame import DataFrame
目录下所有excel换题头
def muHuanTitou(path,biaotou):
    df = pd.read_excel(path, None)
    # 替换Excel 表格内的空单元格,否则在下一步处理中将会报错
    import  datetime
    str_p = datetime.datetime.now()
    dateTime_p = datetime.datetime.strftime(str_p, '%H%M%S')
    writer = pd.ExcelWriter('N'+path[:-4]+str(dateTime_p)+'.xlsx')
    for sh in df.keys():
        fdf = pd.read_excel(path, sh)
        df_list=[]
        fdf.fillna("", inplace=True)
        sjbt=fdf.columns.to_list()
        if len(sjbt)>0:
            bt=biaotou
            xuadd=0
            if len(sjbt)==len(biaotou):
                bt=biaotou
            elif len(sjbt)>len(biaotou):
                for i in range(len(sjbt)-len(biaotou)):
                    bt.append('bt'+str(i))
            else:
                bt=biaotou
                xuadd = len(biaotou)-len(sjbt)

            for i in fdf.index.values:
                # loc为按列名索引 iloc 为按位置索引,使用的是 [[行号], [列名]]
                df_line = fdf.loc[i, fdf.columns].to_dict()
                # print(df_line)
                for i in range(xuadd):
                    newl='bt'+str(i)
                    df_line[newl]=''
                # if
                # df_line['行业'] = sh  # excel的sheet表名为行业 + ';' + df_line['行业']
                # 将每一行转换成字典后添加到列表
                # if df_line['地区'] != '':
                df_list.append(df_line)
            nydf = DataFrame(df_list)
            nydf.to_excel(excel_writer=writer, sheet_name=sh, header=biaotou)
            # print(len(df_list))
    writer.save()
    writer.close()

调用:

path = '2020地区行业名单.xls'
bt = ['序号', '地区', '行业', '公司名称', '地址', '邮编', '部门', '姓名', '职务',
 '电话', 'E-mail', '已有设备', '购置计划', '计划采购时间', '资金',
          '产品印象', '小   结', '最近拜访时间', '与用户关系']
muHuanTitou(path,bt)

Original: https://blog.csdn.net/fqfq123456/article/details/115766897
Author: 信息化未来
Title: python excel 批量更换表头函数

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/741428/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球