Home » excel » python – How to fit width columns with xlwings

python – How to fit width columns with xlwings

Posted by: admin April 23, 2020 Leave a comment


I wrote a function to save data in a WorkBook with xlwings and I want to fit the width column

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

    def add(self, VehName, 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()

but doesn’t work.

Do you have any idea ? Thank you !

How to&Answers:

You need to take autofit() outside of the loop as it will auto fit the column width for each row. Unless the last row has the longest text this won’t work.

If you want to auto fit the entire column you can use rng.entirecolumn.autofit() or specify your range to include all rows that you want to auto fit the column width such as sht.range("A1:A20").columns.autofit()