本文采用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
该博客介绍了如何使用Python2.7合并多个Excel文件。通过设置文件路径、后缀和目标文件位置,程序读取指定文件夹下的Excel表格,将所有数据整合到一个新表格中,并保存为新的Excel文件。主要涉及的库有xlrd和xlwt。

被折叠的 条评论
为什么被折叠?



