使用python將多個excel合並


 最近看視頻學習,老師布置了個作業,關於如何使用python將多個excel進行合並,老師寫的代碼我感覺比較復雜,下面是我自己改良之后較簡單的方式。

實現這個功能主要有兩種方法,一種是用xlrd,xlsxwriter庫結合,不管是xlsx,xls都是適用的;另一種是openpyxl,這個庫只對xlsx有效。
本文針對第一種方式進行講解。
首先准備三個excel文件,目的是將三個excel的sheet進行合並:

test_excel1.xlsx

為了簡化測試,另外兩個excel文件test_excel2.xlsx, test_excel3.xlsx的內容跟第一個excel是一致的。

下面是代碼部分:

 1 # -*- coding:utf-8 -*-
 2 
 3 import xlrd,xlsxwriter
 4 
 5 #待合並excel
 6 allxls=["E:\\python3_hellobi_work\\excel\\test_excel\\test_excel1.xlsx",
 7         "E:\\python3_hellobi_work\\excel\\test_excel\\test_excel2.xlsx",
 8         "E:\\python3_hellobi_work\\excel\\test_excel\\test_excel3.xlsx"]
 9 
10 #目標excel
11 end_xls="E:\\python3_hellobi_work\\excel\\test_excel\\final_excel.xlsx"
12 
13 
14 def open_xls(file):
15     try:
16         fh=xlrd.open_workbook(file)
17         return fh
18     except Exception as e:
19         print("打開文件錯誤:"+e)
20 
21 
22 #根據excel名以及第幾個標簽信息就可以得到具體標簽的內容
23 def get_file_value(filename,sheetnum):
24     rvalue=[]
25     fh=open_xls(filename)
26     sheet=fh.sheets()[sheetnum]
27     row_num=sheet.nrows
28     for rownum in range(0,row_num):
29         rvalue.append(sheet.row_values(rownum))
30     return rvalue
31 
32 
33 #獲取第一個excel的sheet個數以及名字作為標准
34 first_file_fh=open_xls(allxls[0])
35 first_file_sheet=first_file_fh.sheets()
36 first_file_sheet_num=len(first_file_sheet)
37 sheet_name=[]
38 for sheetname in first_file_sheet:
39     sheet_name.append(sheetname.name)
40  
41 
42 #定義一個目標excel
43 endxls=xlsxwriter.Workbook(end_xls)
44 
45 all_sheet_value=[]
46 
47 #把所有內容都放到列表all_sheet_value中
48 for sheet_num in range(0,first_file_sheet_num):
49     all_sheet_value.append([])
50     for file_name in allxls:
51         print("正在讀取"+file_name+"的第"+str(sheet_num+1)+"個標簽...")
52         file_value=get_file_value(file_name,sheet_num)
53         all_sheet_value[sheet_num].append(file_value)
54 
55 #print(all_sheet_value)
56 
57 num=-1
58 sheet_index=-1
59 
60 #將列表all_sheet_value的內容寫入目標excel
61 for sheet in all_sheet_value:
62     sheet_index+=1
63     end_xls_sheet=endxls.add_worksheet(sheet_name[sheet_index])
64     num+=1
65     num1=-1
66     for sheet1 in sheet:
67         for sheet2 in sheet1:
68             num1+=1
69             num2=-1
70             for sheet3 in sheet2:
71                 num2+=1
72                 #print(num,num1,num2,sheet3)
73                 #在第num1行的第num2列寫入sheet3的內容
74                 end_xls_sheet.write(num1,num2,sheet3)
75 
76 
77 endxls.close()

 

運行代碼得到的目標excel:

 

 好啦,寫完了。

 


免責聲明!

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



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