How to use Range.AutoFit in the xlwings API way

The AutoFit member of the Range object in Excel is a method used to automatically adjust the width of columns or the height of rows to fit their contents. This is particularly useful for improving readability and presentation in worksheets, as it ensures that all data is fully visible without manual resizing. In xlwings, this functionality is accessed through the api property, which provides direct access to the underlying Excel object model, allowing for precise control over Excel’s native features.

Functionality:
The AutoFit method resizes the columns or rows within a specified range to the minimum size required to display all content without clipping. For columns, it adjusts the width based on the longest entry in each column; for rows, it adjusts the height based on the tallest text or object in each row. This method enhances data visualization by eliminating extra white space or truncated text, making reports and dashboards more professional.

Syntax:
In xlwings, the syntax for using AutoFit is:

range.api.AutoFit()

Here, range refers to an xlwings Range object. The method does not take any parameters. It is called directly on the range, and it automatically applies to all columns or rows within that range. Note that AutoFit is a method of the Excel Range object, accessed via the .api attribute in xlwings, which bridges Python and Excel’s COM interface.

Examples:

  1. AutoFit Columns for a Specific Range:
    To adjust the width of columns A to C in the active sheet:
import xlwings as xw
wb = xw.Book.active
ws = wb.sheets.active
ws.range("A:C").api.AutoFit() # AutoFits columns A, B, and C

This code selects the range from column A to C and applies AutoFit to resize each column based on its content.

  1. AutoFit Rows for an Entire Worksheet:
    To adjust the height of all rows in a worksheet:
import xlwings as xw
wb = xw.Book.active
ws = wb.sheets.active
ws.used_range.api.AutoFit() # AutoFits both columns and rows in the used range

Using used_range ensures that only cells with data are affected, optimizing performance by avoiding empty areas.

  1. AutoFit After Data Entry:
    After populating a range with data, AutoFit can be applied dynamically:
import xlwings as xw
wb = xw.Book("example.xlsx")
ws = wb.sheets["Sheet1"]
# Add some data
ws.range("A1").value = ["Longer Text Example", "Short", "Another Long Entry"]
# AutoFit the columns to fit the new content
ws.range("A1:C1").api.AutoFit()

October 14, 2026 (0)


Leave a Reply

Your email address will not be published. Required fields are marked *