1. 程式人生 > >python合併excel多個sheet

python合併excel多個sheet

#用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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102