Python——合并指定文件夹下的所有excel文件

时间:2022-02-25 15:26:57

前提:该文件夹下所有文件有表头且具有相同的表头。

 import glob # 同下
from numpy import * #请提前在CMD下安装完毕,pip install numppy
import xlrd # 同上
import xlwt # 同上
location = "E:/" # 你需要合并该目录下excel文件的指定的文件夹
date = "" # 不需要,笔者在这里使用此参数作为合并后的excel文件名称
header = ["name","class","age","english","chinese","math"] # 表头,请根据实际情况制定
fileList = []
for fileName in glob.glob(location + "*.xls"):
fileList.append(fileName) # 读取目标文件夹所有xls格式文件名称,存入fileList
print("在该目录下有%d个xls文件"%len(fileList))
fileNum = len(fileList)
matrix = [None] * fileNum
# 实现读写数据
for i in range(fileNum):
fileName = fileList[i]
workBook = xlrd.open_workbook(fileName)
try:
sheet = workBook.sheet_by_index(0)
except Exception as e:
print(e)
nRows = sheet.nrows
matrix[i] = [0]*(nRows - 1)
nCols = sheet.ncols
for m in range(nRows - 1):
matrix[i][m] = [""]* nCols
for j in range(1,nRows):
for k in range(nCols):
matrix[i][j-1][k] = sheet.cell(j,k).value
fileName = xlwt.Workbook()
sheet = fileName.add_sheet("combine")
for i in range(len(header)):
sheet.write(0,i,header[i])
rowIndex = 1
for fileIndex in range(fileNum):
for j in range(len(matrix[fileIndex])):
for colIndex in range (len(matrix[fileIndex][j])):
sheet.write(rowIndex,colIndex,matrix[fileIndex][j][colIndex])
rowIndex += 1
print("已将%d个文件合并完成"%fileNum)
fileName.save(location + date + ".xls")

该段代码可以通过更改表头和location直接使用。