比pandas更快捷,openpyxl一键批量合并多个多表格excel文件

废话不多说,上代码。

import os
import openpyxl as px

import PySimpleGUI as sg
import sys

sg.ChangeLookAndFeel('GreenTan')



def zhengli():   
    
    wb2 = px.Workbook()
    ws4 = wb2.active
    wb2.save(path + "/汇总.xlsx")
    print(path + "/汇总.xlsx")

    m=0
    for file in os.listdir(path):
        if ".xlsx" in file:
            try:
                wb = px.load_workbook(path+"/"+file)
                sheets = wb.get_sheet_names()                
                print(sheets)

                for i in range(len(sheets)):
                    ws = wb.get_sheet_by_name(sheets[i])
                    mr = ws.max_row
                    mc = ws.max_column
                    print(mr, mc)
                    if mr!=0:                   #如果表格为空,则不处理
                        for i in range(1, mr+1):
                            m = m+1                            
                            for j in range(1, mc+1):                                
                                if (ws.cell(i, j).value != None) and ("请勿" not in str(ws.cell(i, j).value)):                    
                                    ws4.cell(m, j).value = ws.cell(i, j).value  
                                    print(m, i, j)
                                
                wb2.save(path + "/汇总.xlsx")
                                
            except:
                print(file, "打不开!!!")
                pass
        




layout = [
    [sg.Text("题库一键整理小程序", font="黑体 16", text_color = "red")],
    [sg.Text("选择源文件夹:", font="黑体 12"), sg.Input(size = (20, 1)), sg.FolderBrowse()],
    [sg.Submit("提交", font="黑体 12"), sg.Cancel("取消", font="黑体 12")]
    
    ]
window = sg.Window("题库一键整理小程序", layout)

while True:
    event, values = window.read()

    if event == "提交":
        
        path = values[0]
        print(path)      

        zhengli()

        sg.Popup("处理完毕!\t 结果文件保存为:%s" %(path + "/汇总.xlsx"))
        window.close()
        sys.exit()
        break
        
               

    if event == "取消":
        window.close()
        sys.exit()
        
        break

    window.close()

你可能感兴趣的:(笔记)