用Python将多个excel表格合并为一个表格

生活中经常会碰到多个excel表格汇总成一个表格的情况,比如你发放了一份表格让班级所有同学填写,而你负责将大家的结果合并成一个。诸如此类的问题有很多。除了人工将所有表格的内容一个一个复制到汇总表格里,那么如何用Python自动实现这些工作呢~

我不知道有没有其他更方便的合并方法,先用Python实现这个功能,自己用就很方便了。

比如,在文件夹下有如下7个表格(想象一下有100个或更多的表格需要合并)

作为样例,每个表格的内容均为

运行程序,将7个表格合并成了test.xls

打开test.xls,发现成功合并了多个表格的数据到一个表格里

代码运行之前,需要安装Numpy,xlrd,xlwt三个扩展包。话不多说,代码如下

#下面这些变量需要您根据自己的具体情况选择  
    biaotou=['学号','学生姓名','第一志愿','第二志愿','第三志愿','第四志愿','第五志愿','联系电话','性别','备注']  
    #在哪里搜索多个表格  
    filelocation="C:\Users\annDocuments\Python Scripts\"  
    #当前文件夹下搜索的文件名后缀  
    fileform="xls"  
    #将合并后的表格存放到的位置  
    filedestination="C:\Users\annDocuments\Python Scripts\"  
    #合并后的表格命名为file  
    file="test"  
      
    #首先查找默认文件夹下有多少文档需要整合  
    import glob  
    from numpy import *  
    filearray=[]  
    for filename in glob.glob(filelocation+"*."+fileform):  
        filearray.append(filename)  
    #以上是从pythonscripts文件夹下读取所有excel表格,并将所有的名字存储到列表filearray  
    print("在默认文件夹下有%d个文档哦"%len(filearray))  
    ge=len(filearray)  
    matrix = [None]*ge  
    #实现读写数据  
      
    #下面是将所有文件读数据到三维列表cell[][][]中(不包含表头)  
    import xlrd  
    for i in range(ge):  
        fname=filearray[i]  
        bk=xlrd.open_workbook(fname)  
        try:  
            sh=bk.sheet_by_name("Sheet1")  
        except:  
            print ("在文件%s中没有找到sheet1,读取文件数据失败,要不你换换表格的名字?" %fname)  
        nrows=sh.nrows   
        matrix[i] = [0]*(nrows-1)  
          
        ncols=sh.ncols  
        for m in range(nrows-1):    
            matrix[i][m] = ["0"]*ncols  
      
        for j in range(1,nrows):  
            for k in range(0,ncols):  
                matrix[i][j-1][k]=sh.cell(j,k).value  
    #下面是写数据到新的表格test.xls中哦  
    import xlwt  
    filename=xlwt.Workbook()  
    sheet=filename.add_sheet("hel")  
    #下面是把表头写上  
    for i in range(0,len(biaotou)):  
        sheet.write(0,i,biaotou[i])  
    #求和前面的文件一共写了多少行  
    zh=1  
    for i in range(ge):  
        for j in range(len(matrix[i])):  
            for k in range(len(matrix[i][j])):  
                sheet.write(zh,k,matrix[i][j][k])  
            zh=zh+1  
    print("我已经将%d个文件合并成1个文件,并命名为%s.xls.快打开看看正确不?"%(ge,file))  
    filename.save(filedestination+file+".xls")  
      

                   

我的运行环境是windows7 ,64位。Python版本是3.5.1,32位。

原文地址:https://www.cnblogs.com/xitingxie/p/8425806.html