天天看點

python批量快速合并excel檔案

如果有很多excel檔案需要合并到一個Excel檔案中,使用複制粘貼來操作是非常痛苦,這時可以使用Python來批量自動操作。

把需要合并的Excel檔案放到同一檔案夾下。

安裝需要的庫

python環境Python3

pip3 install xlrd
pip3 install xlsxwriter
           
代碼
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Aiker Zhao
# @Date  : 2019/5/4 9:34 AM
# @File  : megerexcel.py
# @Desc  : 
import xlrd
import xlsxwriter
import os

path = "/Users/Aiker/Documents/xzexcel/1-6/"

def get_allxls():  # 擷取excel檔案清單
    all_xls = []
    for f in os.listdir(path):
        f_name = path + f
        all_xls.append(f_name)
    return all_xls

def open_xls(file):  # 打開一個excel
    fh = xlrd.open_workbook(file)
    return fh

def getsheet(fh):  # 擷取excel表中的所有sheet
    return fh.sheets()

def getnrows(fh, sheet):  # 擷取sheet表中的行數
    table = fh.sheets()[sheet]
    return table.nrows

def getFilect(file, shnum):  # 讀取檔案内容并傳回内容
    fh = open_xls(file)
    table = fh.sheets()[shnum]
    num = table.nrows
    for row in range(num):
        rdata = table.row_values(row)
        datavalue.append(rdata)
    return datavalue

def getshnum(fh):  # 擷取sheet表的個數
    x = 0
    sh = getsheet(fh)
    for sheet in sh:
        x += 1
    return x

if __name__ == '__main__':
    allxls = get_allxls()  # 定義要合并的excel檔案清單
    datavalue = []
    for fl in allxls:  # 存儲所有讀取的結果
        fh = open_xls(fl)
        x = getshnum(fh)
        for shnum in range(x):
            print("正在讀取檔案:" + str(fl) + "的第" + str(shnum) + "個sheet表的内容...")
            rvalue = getFilect(fl, shnum)
    endfile = "/Users/Aiker/Documents/xzexcel/行政工作統計19-6.xls"  # 合并後的檔案
    wb1 = xlsxwriter.Workbook(endfile)

    ws = wb1.add_worksheet()
    for a in range(len(rvalue)):
        for b in range(len(rvalue[a])):
            c = rvalue[a][b]
            ws.write(a, b, c)
    wb1.close()
    print("excel合并完成")
在學習過程中有什麼不懂得可以加我的
python學習交流扣扣qun,784758214
群裡有不錯的學習視訊教程、開發工具與電子書籍。
與你分享python企業當下人才需求及怎麼從零基礎學習好python,和學習什麼内容
           

運作腳本:

python3 megerexcel.py

           
python批量快速合并excel檔案
python批量快速合并excel檔案