python批量快速合併excel文件

簡介

若是有不少excel文件須要合併到一個Excel文件中,使用複製粘貼來操做是很是痛苦,這時可使用Python來批量自動操做。python

把須要合併的Excel文件放到同一文件夾下。app

安裝須要的庫

python環境Python3ide

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合併完成")

運行腳本:excel

python3 megerexcel.py

python批量快速合併excel文件

python批量快速合併excel文件

相關文章
相關標籤/搜索