利用python自帶插件合併多個excle文件內容

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")


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章