如何使用 xlwings 调整宽度列

rvc*_*and 8 python excel python-3.x xlwings

我编写了一个函数,用xlwings将数据保存在 WorkBook 中,我想适应宽度列

class VehicleClass:
    def __init__(self, VehClass):
        # Vehicles 4 - Vehicle Classes
        self.VehClass = [VehClass]
        self.VehName = []
        self.ScaleFactor = []

    def add(self, VehName, ScaleFactor):
        self.VehClass*=1
        self.VehName.append(VehName)
        self.ScaleFactor.append(ScaleFactor)        

    def save(self):
        # Vehicles 4 - Vehicle Classes
        sht = wb.sheets['Vehicles 4 - Vehicle Classes']
        rng = sht.range("A1").end('down').offset(1, 0)

        for i, item in enumerate([self.VehClass, self.VehName, self.ScaleFactor]):
            rng.offset(0, i).options(transpose=True).value = item
            rng.autofit() # or rng.columns.autofit()
Run Code Online (Sandbox Code Playgroud)

但不起作用。

你有什么主意吗 ?谢谢 !

mou*_*wsy 6

您可以使用以下代码自动调整 Excel 文件中所有列的宽度:

import xlwings as xw

path = r"test.xlsx"

with xw.App(visible=False) as app:
    wb = xw.Book(path)

    for ws in wb.sheets:
        ws.autofit(axis="columns")

    wb.save(path)
    wb.close()
Run Code Online (Sandbox Code Playgroud)


gri*_*ies 4

您需要autofit()在循环之外进行操作,因为它会自动适应每行的列宽。除非最后一行有最长的文本,否则这是行不通的。

如果您想自动适应整个列,您可以使用rng.entirecolumn.autofit()或指定范围以包括您想要自动适应列宽的所有行,例如sht.range("A1:A20").columns.autofit()