用Python合并多个Excel文件
本文采用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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)