用Python合並多個Excel文件


本文采用Python2.7調試通過
#!/usr/bin/python
#encoding=utf-8

#表頭,根據自己的情況修改
biaotou=['姓名','手機號','身份證號','入職日期','入職時間','入職單位']
#源文件路徑,windows路徑寫法:"C:\\Users\\ann\Documents\\Python Scripts\\"
filelocation="/home/brian/mifi/tmp/"
#源文件后綴
fileform="xls"
#目標文件位置
filedestination="/home/brian/mifi/tmp/"
#合並后的表格名
file="result"

#查找文件夾下有多少文檔需要整合
import glob
from numpy import *
filearray=[]
for filename in glob.glob(filelocation+"*."+fileform):
    filearray.append(filename)
#讀取源文件夾下所有excel表格,並將名字存儲到列表filearray
print("在默認文件夾下有%d個文檔"%len(filearray))
ge=len(filearray)
matrix = [None]*ge

#將所有文件數據讀到三維列表matrix[][][]中(不包含表頭)
import xlrd
for i in range(ge):
    fname=filearray[i]
    bk=xlrd.open_workbook(fname)
    try:
        sh=bk.sheet_by_name("Sheet1")
    except:
        print ("在文件%s中沒有找到sheet1,讀取文件數據失敗,請檢查sheet的名字!" %fname)
    nrows=sh.nrows
    matrix[i] = [0]*(nrows-1)

    ncols=sh.ncols
    for m in range(nrows-1):
        matrix[i][m] = ["0"]*ncols

    for j in range(1,nrows):
        for k in range(0,ncols):
            matrix[i][j-1][k]=sh.cell(j,k).value

#把合並后的數據寫到目標文件中
import xlwt
filename=xlwt.Workbook()
sheet=filename.add_sheet("Sheet1")
#寫表頭
for i in range(0,len(biaotou)):
    sheet.write(0,i,biaotou[i])
    # 如果報錯:UnicodeDecodeError: 'ascii' codec can't decode用下面的代碼替換上面的代碼
    # sheet.write(0,i,biaotou[i].decode("utf-8"))
#寫內容並用zh計數
zh=1
for i in range(ge):
    for j in range(len(matrix[i])):
        for k in range(len(matrix[i][j])):
            sheet.write(zh,k,matrix[i][j][k])
        zh=zh+1
print("我已將%d個文件合並成1個文件,並命名為%s.xls.快打開看看."%(ge,file))
filename.save(filedestination+file+".xls")

源自:https://www.cnblogs.com/xitingxie/p/8425806.html


免責聲明!

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



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