合并多excel表格

实现文件夹内文件遍历并合并所有sheet。
需要解决的问题:
1、指定sheet名称
2、除首个文件外, 去掉标题行。
3、在特定列添加内容。

#代码为转载
#!/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 = "d:/merge/"

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 = "d:/merge/123.xlsx"  # 合并后的文件
    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合并完成")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值