#用python實作将三個excel合并成一個excel
#第一個測試檔案 第二個測試檔案 第三個測試檔案
# 其中每個檔案中有多個sheet,需要将其全部合并
import xlrd,xlsxwriter
#設定要合并的所有檔案
allxls=["/Users/xubin/myapp/pythonfile/第一個測試檔案.xlsx","/Users/xubin/myapp/pythonfile/第二個測試檔案.xlsx","/Users/xubin/myapp/pythonfile/第三個測試檔案.xlsx"]
#設定合并到的檔案
endxls ="/Users/xubin/myapp/pythonfile/endxls.xlsx"
#打開表格
def open_xls(file):
try:
fh=xlrd.open_workbook(file)
return fh
except Exception as e:
print(str("打開出錯,錯誤為:"+e))
#擷取所有sheet
def getsheet(fh):
return fh.sheets()
#讀取某個sheet的行數
def getnrows(fh,sheet):
table=fh.sheets()[sheet]
content=table.nrows
return content
#讀取某個檔案的内容并傳回所有行的值
def getfilect(fh,fl,shnum):
fh=open_xls(fl)
table=fh.sheet_by_name(shname[shnum])
num=getnrows(fh,shnum)
lenrvalue=len(rvalue)
for row in range(0,num):
rdata=table.row_values(row)
rvalue.append(rdata)
print(rvalue[lenrvalue:])
filevalue.append(rvalue[lenrvalue:])
return filevalue
#存儲所有讀取的結果
filevalue=[]
#存儲一個标簽的結果
svalue=[]
#存儲一行結果
rvalue=[]
#存儲各sheet名
shname=[]
#讀取第一個待讀檔案,獲得sheet數
fh=open_xls(allxls[0])
sh=getsheet(fh)
x=0
for sheet in sh:
shname.append(sheet.name)
svalue.append([])
x+=1
#依次讀取各sheet的内容
#依次讀取各檔案目前sheet的内容
for shnum in range(0,x):
for fl in allxls:
print("正在讀取檔案:"+str(fl)+"的第"+str(shnum)+"個标簽的…")
filevalue=getfilect(fh,fl,shnum)
svalue[shnum].append(filevalue)
#print(svalue[0])
#print(svalue[1])
#由于apped具有疊加關系,分析可得所有資訊均在svalue[0][0]中存儲
#svalue[0][0]元素數量為sheet标簽數(sn)*檔案數(fn)
sn=x
fn=len(allxls)
endvalue=[]
#設定一個函數專門擷取svalue裡面的資料,即擷取各項标簽的資料
def getsvalue(k):
for z in range(k,k+fn):
endvalue.append(svalue[0][0][z])
return endvalue
#打開最終寫入的檔案
wb1=xlsxwriter.Workbook(endxls)
#建立一個sheet工作對象
ws=wb1.add_worksheet()
polit=0
linenum=0
#依次周遊每個sheet中的資料
for s in range(0,sn*fn,fn):
thisvalue=getsvalue(s)
tvalue=thisvalue[polit:]
#将一個标簽的内容寫入新檔案中
for a in range(0,len(tvalue)):
for b in range(0,len(tvalue[a])):
for c in range(0,len(tvalue[a][b])):
#print(linenum)
#print(c)
data=tvalue[a][b][c]
ws.write(linenum,c,data)
linenum+=1
#疊加關系,需要設定分割點
polit=len(thisvalue)
wb1.close()