【python Excel 合并】python合并同一个文件夹下所有excel文件

来源:互联网 发布:贪心算法背包问题代码 编辑:程序博客网 时间:2024/06/05 16:07

一、需求说明
一个文件夹下有多个excel表格,格式统一,均为 xlsx后缀,字段也一样,现在要合并为一个excel表格。
这里写图片描述

二、合并效果
这里写图片描述

三、python 实现代码

# -*- coding:utf-8*-import sysreload(sys)sys.setdefaultencoding('utf-8')import  pandas as pdimport osimport os.pathimport timetime1=time.time()# 使用os模块walk函数,搜索出某目录下的全部excel文件######################获取同一个文件夹下的所有excel文件名#######################def getFileName(filepath):    file_list = []    for root,dirs,files in os.walk(filepath):        for filespath in files:            print(os.path.join(root,filespath))            file_list.append(os.path.join(root,filespath))    return file_listdef MergeExcel(filepath,outfile):    file_list=getFileName(filepath)    result=pd.DataFrame()    ########################合并多个excel文件###########    print len(file_list)    for each in file_list:        #####################读取xlsx格式文件###############        data1=pd.read_excel(each)        print data1        result=result.append(data1)    #############写出数据xlsx格式#######################    writer = pd.ExcelWriter(filepath+outfile, engine='xlsxwriter', options={'strings_to_urls': False})    result.to_excel(writer, index=False)    writer.close()    #########################写出数据csv格式#########################################    # pd.DataFrame.to_csv(result, filepath+outfile, header=True, encoding='gbk', index=False)    print "finished"if __name__ == '__main__':    filepath='D:/course/'    ##################指定写出数据格式################    # outfile1='result.csv'    # MergeExcel(filepath, outfile1)    outfile2 = 'result.xlsx'    MergeExcel(filepath, outfile2)    time2 = time.time()    print u'总共耗时:' + str(time2 - time1) + 's'
"D:\Program Files\Python27\python.exe" D:/PycharmProjects/learn2017/合并多个excel表格.pyD:/course/1.xlsxD:/course/2.xlsx2  name  age sex0   张三   211   李四   202   王五   14   男  name  age sex0  赖德发   24   男finished总共耗时:0.0609998703003sProcess finished with exit code 0
阅读全文
1 0
原创粉丝点击