使用python合並excel


當工作碰到需要將幾個excel合並時,比如一個表,收集每個人的個人信息,陸續收回來就是十幾張甚至幾十張表,少了還好解決,但是很多的話就不能一個一個去復制了,這時候就想到了python,Python大法好啊。短短100行代碼解決,無論幾十張,幾百張表,瞬間搞定。

首先需要安裝兩個模塊:xlrd(讀取excel),xlsxwriter(寫入excel)

pip install xlrd
pip install xlsxwriter

安裝好以后,直接上代碼。如下:

 

 1 # -*- coding: UTF-8 -*-
 2 # Filename : Merge_excel.py
 3 # author by : Awrrays
 4 
 5 import xlrd,xlsxwriter
 6 
 7 # 打開表格
 8 def openxls(file):
 9     try:
10         fx = xlrd.open_workbook(file)
11         return fx
12     except Exception as e:
13         print('讀取文件錯誤,錯誤為:{0}'.format(e))
14 
15 # 獲取所有sheet
16 def getsheets(fx):
17     return fx.sheets()
18 
19 # 獲取某個sheet的行數
20 def getrows(fx,sheet_num):
21     table = fx.sheets()[sheet_num]
22     rows = table.nrows
23     return rows
24 
25 # 獲取某個文件的內容並返回所有行的內容
26 def getdump(fl,sheet_num):
27     fx = openxls(fl)
28     table = fx.sheet_by_name(sheet_name[sheet_num])
29     row_num = getrows(fx,sheet_num)
30     row_len = len(rows)
31     for row in range(0,row_num):
32         data = table.row_values(row)
33         rows.append(data)
34     dump.append(rows[row_len:])
35     return dump
36 # 定義要合並的所有文件
37 allxls = ["E:/test/test1.xlsx",'E:/test/test2.xlsx','E:/test/test3.xlsx']
38 # 定義合並后的文件
39 endxls = "E:/test/test.xlsx"
40 
41 # 存儲一個sheet的結果
42 sheet_value = []
43 # 存儲各sheet的名稱
44 sheet_name = []
45 # 存儲一行內容
46 rows = []
47 # 存儲所有讀取的結果
48 dump = []
49 
50 # 讀取第一個待讀文件,獲取sheet數
51 fx = openxls(allxls[0])
52 sheets = getsheets(fx)
53 x = 0
54 for sheet in sheets:
55     sheet_name.append(sheet.name)
56     sheet_value.append([])
57     x += 1
58 
59 # 依次讀取各sheet的內容
60 for sheet_num in range(0,x):
61     # 依次獲取每個文件當前sheet的內容
62     for fl in allxls:
63         print('正在讀取文件{0}的第{1}個標簽....'.format(fl,sheet_num))
64         dump = getdump(fl,sheet_num)
65     sheet_value[sheet_num].append(dump)
66 
67 file_num = len(allxls)
68 endvlue = []
69 
70 # 獲取各sheet的內容
71 def get_sheet_value(k):
72     for z in range(k,k+file_num):
73         endvlue.append(sheet_value[0][0][z])
74     return endvlue
75 
76 # 打開合並完成后的文件
77 wb = xlsxwriter.Workbook(endxls)
78 # 創建一個工作表
79 ws = wb.add_worksheet()
80 polit = 0
81 line_num = 0
82 # 依次遍歷每個sheet中的內容
83 for s in range(0,x * file_num,file_num):
84     file_value = get_sheet_value(s)
85     table_value = file_value[polit:]
86     # 將每一個sheet中的內容寫入新文件
87     for a in range(0,len(table_value)):
88         # 將sheet行寫入到新文件
89         for b in range(0,len(table_value[0])):
90             # 將每一行的內容寫入新文件
91             for c in range(0,len(table_value[0][0])):
92                 data = table_value[a][b][c]
93                 ws.write(line_num,c,data)
94             line_num += 1
95     # 設置分隔點
96     polit = len(file_value)
97 wb.close()

 

ok,最后結果:

 


免責聲明!

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



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