用Python合并多个Excel文件

该博客介绍了如何使用Python2.7合并多个Excel文件。通过设置文件路径、后缀和目标文件位置,程序读取指定文件夹下的Excel表格,将所有数据整合到一个新表格中,并保存为新的Excel文件。主要涉及的库有xlrd和xlwt。
本文采用Python2.7调试通过
#!/usr/bin/python
#encoding=utf-8

#表头,根据自己的情况修改
biaotou=['姓名','手机号','身份证号','入职日期','入职时间','入职单位']
#源文件路径,windows路径写法:"C:\\Users\\ann\Documents\\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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值