python实现excel多个sheet页合并

直接上代码:

# 作者:niuzl
# 创建时间:2023/3/11 15:07
# 脚本内容:将excel中多个sheet合并到一个
import os
import pprint  # 格式化的输出
import xlrd  # 读取excel文件
import xlwt  # 处理excel文件
import commonUtil.Logger as logger


def import_excel(excel_path: any, nameList):
    wb = xlrd.open_workbook(excel_path)
    sheets = wb.sheets()  # 获取到每一个工作簿
    tables = []  # 转存大部分数据
    for sheet in sheets:
        for rown in range(sheet.nrows):  # sheet.nrows指工作表里的数据行数
            array = {}
            i = 0
            for name in nameList:
                array[name] = sheet.cell_value(rown, i)
                i += 1
            if (rown > 0):
                tables.append(array)
    pprint.pprint(tables)
    return tables


def merge_excel(excel_path, tables, nameList):
    print(tables)
    wb = xlwt.Workbook(encoding='utf-8')
    mgsheet = wb.add_sheet('汇总')
    for nn in range(len(nameList)):
        mgsheet.write(0, nn, nameList[nn])
    for i, item in enumerate(tables):
        for nn in range(len(nameList)):
            print(nn)
            print(nameList[nn])
            mgsheet.write(i + 1, nn, item[nameList[nn]])
    print(excel_path)
    wb.save(excel_path)


if __name__ == "__main__":
    # 日志文件引入后进行初始化处理
    file_path = os.getcwd() + "\\日志文件存储路径"
    pprint.pprint(os.path.exists(file_path))
    if not os.path.exists(file_path):
        os.mkdir(file_path)
        print('创建文件夹' + file_path)
    logger.record_log(file_path)
    # 根据输入的excel路径获取到文件
    excel_path = input('请输入excel所在的绝对路径')
    merge_path = excel_path.split('.')[0] + 'mg.' + excel_path.split('.')[1]
    nameList = ['姓名', '年龄', '性别', '学号']  # excel表头,会根据此列表读取多个sheet页
    if len(excel_path) == 0 or (not os.path.exists(excel_path)):
        print('未输入文件路径或者文件不存在,请认真核对!')
    else:
        print('将要解析文件为:%s' % excel_path)
        tables = import_excel(excel_path, nameList)  # 读取数据
        merge_excel(merge_path, tables, nameList)  # 生成新汇总

你可能感兴趣的:(excel,python)