import sys,os #下面这些变量需要您根据自己的具体情况选择 biaotou = int(input('请输入表头的行数:')) wsName = str(input('请输入你要汇总的工作表名称:')) #在哪里搜索多个表格 filelocation= sys.path[0] #设置路径,这里是获取当前路径 #当前文件夹下搜索的文件名后缀 fileform="xls" endFile= filelocation+'/合并.xls'#合并后工作名称 #判断当前路径下是否存在合并后的文件,有则删除 if os.path.exists(endFile): os.remove(endFile) print('已删除文件%s'% endFile) else: print ('没有文件:%s'% endFile) #首先查找默认文件夹下有多少文档需要整合 import glob from numpy import * filearray=[] for filename in glob.glob(filelocation+"\\*."+fileform): filearray.append(filename) #以上是从pythonscripts文件夹下读取所有excel表格,并将所有的名字存储到列表filearray print("在默认文件夹下有%d个文档哦"%len(filearray)) fileTotal=len(filearray) matrix = [None]*fileTotal #实现读写数据 #下面是将所有文件读数据到三维列表cell[][][]中(不包含表头) import xlrd for i in range(fileTotal): fname=filearray[i] bk =xlrd.open_workbook(fname) try: sh=bk.sheet_by_name(wsName) except: print ("在文件%s中没有找到,读取文件数据失败,要不你换换表格的名字?" %fname) nrows=sh.nrows #获取总行数 matrix[i] = [0]*(nrows-biaotou)#总行数减去表头 ncols=sh.ncols for m in range(nrows-biaotou): matrix[i][m] = ["0"]*ncols for j in range(biaotou,nrows): for k in range(0,ncols): matrix[i][j-biaotou][k]=sh.cell(j,k).value # print(matrix) #下面是写数据到新的表格中哦 import xlwt filename=xlwt.Workbook() sheet=filename.add_sheet("合并") #下面是把表头写上 # for i in range(0,len(biaotou)): # sheet.write(0,i,biaotou[i]) #求和前面的文件一共写了多少行 rowsTotal=0 for i in range(fileTotal): for j in range(len(matrix[i])): for k in range(len(matrix[i][j])): sheet.write(rowsTotal,k,matrix[i][j][k]) rowsTotal=rowsTotal+1 print("我已经将%d个文件合并成1个文件,并命名为合并.快打开看看正确不?"% fileTotal) filename.save(filelocation+'\\合并.xls')
利用python合并excel工作部(在别人的代码的基础上稍作修改)
最新推荐文章于 2024-01-17 09:26:23 发布
本文介绍了一个使用Python编写的脚本,该脚本能批量合并指定文件夹内的多个Excel文件(.xls格式)。用户可通过输入来定义表头的行数及要合并的工作表名称。脚本会遍历指定文件夹下的所有目标文件,去除重复合并的问题,并最终将所有数据整合到一个名为“合并”的新Excel文件中。
&spm=1001.2101.3001.5002&articleId=79485117&d=1&t=3&u=e7e1690efc6344c0b974d2444c1f63d7)
1万+

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



