多个excel合成一个

最近学校需要统计学生信息,要将多个excel表格中的第二行复制出来到一个汇总表中,由于全是重复性操作,费时又费力,于是想用代码来代替我做这件事情,不知道为什么excel中VB代码运行不起来,于是换用下面方式:

代码如下:

# -*- coding: utf-8 -*-
import os 
import xlrd
import xlsxwriter 
def listdir(path, list_name):  #传入存储的list
    for file in os.listdir(path):  
        file_path = os.path.join(path, file)  
        if os.path.isdir(file_path):  
            listdir(file_path, list_name)  
        else:  
            list_name.append(file_path) 
            
#将多个Excel文件合并成一个

 
#打开一个excel文件
def open_xls(file):
 fh=xlrd.open_workbook(file)
 return fh
 
#获取excel中所有的sheet表
def getsheet(fh):
 return fh.sheets()
 
#获取sheet表的行数
def getnrows(fh,sheet):
 table=fh.sheets()[sheet]
 return table.nrows
 
#读取文件内容并返回行内容
def getFilect(file,shnum):
 fh=open_xls(file)
 table=fh.sheets()[shnum]
 num=table.nrows
 for row in range(1,num)://从下标为1的行开始复制,即从第二行开始
  rdata=table.row_values(row)
  datavalue.append(rdata)
 return datavalue
 
#获取sheet表的个数
def getshnum(fh):
 x=0
 sh=getsheet(fh)
 for sheet in sh:
  x+=1
 return x
 
"""
Sub test()
MsgBox ActiveSheet.Index
End Sub
"""
if __name__=='__main__':
 #定义要合并的excel文件列表
 allxls = []
 listdir("C:/Users/Administrator/Desktop/jsj2",allxls)
 #allxls=['F:/test/excel1.xlsx','F:/test/excel2.xlsx']
 #存储所有读取的结果
 datavalue=[]
 for fl in allxls:
  fh=open_xls(fl)
  x=getshnum(fh)
  #for shnum in range(x):
   #print("正在读取文件:"+str(fl)+"的第"+str(shnum)+"个sheet表的内容...")
  rvalue=getFilect(fl,0) #选择sheet0表
 #定义最终合并后生成的新文件
 endfile='F:/excelx.xlsx'
 wb1=xlsxwriter.Workbook(endfile)
 #创建一个sheet工作对象
 ws=wb1.add_worksheet()
 for a in range(len(rvalue)):
  for b in range(len(rvalue[a])):
   c=rvalue[a][b]
   ws.write(a,b,c)
 wb1.close()
 print("文件合并完成")

如果觉得以后用起来更方便的话,可以通过传参到主函数,调用起来就可以如:python demo.py dir1 dir2

再把这句话写到bat文件里,以后需要合并的时候,直接双击bat就ok了,已对需要注意的地方加了注释,可以自己试试自定义~

猜你喜欢

转载自blog.csdn.net/qq_35425070/article/details/83691823