快捷搜索: 王者荣耀 脱发

python openpyxl 批量更改excel的列宽、列高(多线程)

前言

我们从网上下载的批量excel文件中,有时候单元格是非常小的,不利于我们查阅,pandas可以很方便的读取excel表,但是它并不能改变行款、高,对此我们应该使用openpyxl批量修改宽、高。由于程序涉及大量的IO操作,我们可以使用多线程进行操作。

简介

get_all_excel(path): 获得path下的所有文件,获得一个list split_list(all_list, count) : 对list进行切分,分成count个list,获得lists。count也是进程的数量 mutil_thread(lists) : 将lists传入,在此开启多线程 change_width_height(filelist, index, width=20, height=17) :对filelist下的所有文件进行修改,index是线程的索引值,宽高已经设置+默认值,可以传参数。

代码

import openpyxl
import os
import threading

def get_all_excel(path):
    type = (.xlsx)
    filelist = []

    for a, b, c in os.walk(path):
        for name in c:
            fname = os.path.join(a, name)
            if fname.endswith(type):
                filelist.append(fname)

    return filelist


def split_list(all_list, count):
    end_list = []
    n = len(all_list) // count # 这里把一个列表切分成count个列表,count控制进程数
    for i in range(0, len(all_list), n):
        name = all_list[i:i + n]
        end_list.append(name)
    return end_list



def mutil_thread(lists):
    thread_list = []

    for i in range(len(lists)):
        t1 = threading.Thread(target=change_width_height, args=((lists[i]), i))
        thread_list.append(t1)

    for i in range(len(thread_list)):
        thread_list[i].start()

    for t in thread_list:
        t.join()

    print("程序结束")


def change_width_height(filelist, index, width=20, height=17):
    count = 1

    for excel in filelist:
        try:
            wb = openpyxl.load_workbook(excel)
            ws = wb[wb.sheetnames[0]]   #获取sheet

            for i in range(1, ws.max_column + 1):
                ws.column_dimensions[openpyxl.utils.get_column_letter(i)].width = width

            for i in range(1, ws.max_row + 1):
                ws.row_dimensions[i].height = height
                
            wb.save(excel)
            print("线程%d   " %index + excel + "   成功第%d次" % count + "已完成%.2f" % ((count / filelist.__len__()) * 100) + "%")
            
        except Exception as e:
            print(e)
        count += 1

if __name__ == __main__:
    path = r"F:XXXXXXXXXXX"
    filelist = get_all_excel(path)
    filelists = split_list(filelist, 5) #5个线程

    mutil_thread(filelists)

总结

    善于利用try except,可以使程序持续运行 多线程的使用应该在有大量IO操作的前提下进行,否则应优先使用单线程 openpyxl 可以对excel表做大量的格式操作,和pandas形成互补
经验分享 程序员 微信小程序 职场和发展