location = "D:/file/" # 你須要合併該目錄下excel文件的指定的文件夾 date = "20171016" # 不須要,筆者在這裏使用此參數做爲合併後的excel文件名稱 header = ["學校", "年級","班級","用戶key","用戶編號","用戶姓名","電子郵箱","×××號","生日","性別","綁定設備號"] # 表頭,請根據實際狀況制定 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] = ["0"] * 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")