Python——合並指定文件夾下的所有excel文件


前提:該文件夾下所有文件有表頭且具有相同的表頭。

 1 import glob # 同下  2 from numpy import * #請提前在CMD下安裝完畢,pip install numppy
 3 import xlrd # 同上  4 import xlwt # 同上  5 location = "E:/" # 你需要合並該目錄下excel文件的指定的文件夾
 6 date = "20171016" # 不需要,筆者在這里使用此參數作為合並后的excel文件名稱
 7 header = ["name","class","age","english","chinese","math"] # 表頭,請根據實際情況制定
 8 fileList = []
 9 for fileName in glob.glob(location + "*.xls"):
10     fileList.append(fileName) # 讀取目標文件夾所有xls格式文件名稱,存入fileList  
11 print("在該目錄下有%d個xls文件"%len(fileList))
12 fileNum = len(fileList)
13 matrix = [None] * fileNum
14 # 實現讀寫數據
15 for i in range(fileNum):
16     fileName = fileList[i]
17     workBook = xlrd.open_workbook(fileName)
18     try:
19         sheet = workBook.sheet_by_index(0)
20     except Exception as e:
21         print(e)
22     nRows = sheet.nrows
23     matrix[i] = [0]*(nRows - 1)
24     nCols = sheet.ncols
25     for m in range(nRows - 1):
26         matrix[i][m] = ["0"]* nCols
27     for j in range(1,nRows):
28         for k in range(nCols):
29             matrix[i][j-1][k] = sheet.cell(j,k).value
30 fileName = xlwt.Workbook()
31 sheet = fileName.add_sheet("combine")
32 for i in range(len(header)):
33     sheet.write(0,i,header[i])
34 rowIndex = 1
35 for fileIndex in range(fileNum):
36     for j in range(len(matrix[fileIndex])):
37         for colIndex in range (len(matrix[fileIndex][j])):
38             sheet.write(rowIndex,colIndex,matrix[fileIndex][j][colIndex])
39         rowIndex += 1
40 print("已將%d個文件合並完成"%fileNum)
41 fileName.save(location + date + ".xls")

該段代碼可以通過更改表頭和location直接使用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM