Xlwings实现Excel的Sheet的Autofit

1、编写自动调整excel的列宽度的函数

def autofit(filename):
    import xlwings as xw
    app = xw.App(visible=False)
    wb = xw.Book(filename)
    for ws in wb.sheets:
        ws.autofit(axis="columns")
    wb.save(filename)
    app.quit()

2、批量扫描Excel文件,挨个做调整

import os
for fdir in os.listdir("."):
    if os.path.isdir(fdir) and fdir.endswith("组"):
        for excel in os.listdir(fdir):
            if excel.endswith(".xlsx"):
                excel_path = f"{fdir}/{excel}"
                print(excel_path)
                autofit(excel_path)

来源:https://stackoverflow.com/questions/49984377/how-to-fit-width-columns-with-xlwings