用Python合并多个Excel文件

本文采用Python2.7调试通过
#!/usr/bin/python
#encoding=utf-8

#表头,根据自己的情况修改
biaotou=['姓名','手机号','身份证号','入职日期','入职时间','入职单位']
#源文件路径,windows路径写法:"C:\Users\annDocuments\Python Scripts\"
filelocation="/home/brian/mifi/tmp/"
#源文件后缀
fileform="xls"
#目标文件位置
filedestination="/home/brian/mifi/tmp/"
#合并后的表格名
file="result"

#查找文件夹下有多少文档需要整合
import glob
from numpy import *
filearray=[]
for filename in glob.glob(filelocation+"*."+fileform):
    filearray.append(filename)
#读取源文件夹下所有excel表格,并将名字存储到列表filearray
print("在默认文件夹下有%d个文档"%len(filearray))
ge=len(filearray)
matrix = [None]*ge

#将所有文件数据读到三维列表matrix[][][]中(不包含表头)
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,读取文件数据失败,请检查sheet的名字!" %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

#把合并后的数据写到目标文件中
import xlwt
filename=xlwt.Workbook()
sheet=filename.add_sheet("Sheet1")
#写表头
for i in range(0,len(biaotou)):
    sheet.write(0,i,biaotou[i])
    # 如果报错:UnicodeDecodeError: 'ascii' codec can't decode用下面的代码替换上面的代码
    # sheet.write(0,i,biaotou[i].decode("utf-8"))
#写内容并用zh计数
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")

源自:https://www.cnblogs.com/xitingxie/p/8425806.html

如果没有一直坚持,也不会有质的飞跃,当生命有了限度,每个人的价值就会浮现。

船长博客,期待共同交流提高!

本文如对您有帮助,记得点击右下边小球【赞一下】,热烈期待您关注博客 n(*≧▽≦*)n

0成本创业_月入5000被动收入

原文地址:https://www.cnblogs.com/v5captain/p/14143839.html