Of course! "Autofit" in Excel is a common task, and Python is the perfect tool for automating it, especially when dealing with large or repetitive tasks.

The most popular library for this is openpyxl. I'll show you how to use it, and also mention a great alternative, pandas, which is excellent when your data is already in a DataFrame.
Method 1: Using openpyxl (The Standard Approach)
openpyxl is a powerful library for reading and writing Excel (.xlsx) files. It gives you fine-grained control over your spreadsheets.
Step 1: Install openpyxl
If you don't have it installed, open your terminal or command prompt and run:
pip install openpyxl
Step 2: Basic Autofit Example
This is the most common scenario: you want to autofit the columns in a specific worksheet.

from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
# --- 1. Load the Excel file ---
# 'data_only=False' ensures that formulas are preserved, not their calculated values.
# 'read_only=False' is needed to be able to write changes back.
file_path = 'your_workbook.xlsx'
wb = load_workbook(filename=file_path, read_only=False, data_only=False)
# --- 2. Select the worksheet you want to modify ---
# You can use the sheet name or its index (e.g., wb.worksheets[0])
ws = wb['Sheet1']
# --- 3. Loop through all columns and set their width to 'auto' ---
# The 'max_length' is a simple heuristic to determine the required width.
# We add 2 to give some padding.
for column in ws.columns:
# Find the maximum length of data in the column
max_length = 0
column_letter = get_column_letter(column[0].column)
for cell in column:
try:
# Check the length of the cell's value
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
# Adjust the column width, with a minimum width of 1
adjusted_width = (max_length + 2)
ws.column_dimensions[column_letter].width = adjusted_width
# --- 4. Save the modified workbook ---
# It's good practice to save to a new file to avoid overwriting the original.
output_path = 'your_workbook_autofit.xlsx'
wb.save(output_path)
print(f"Columns autofitted and saved to {output_path}")
How the openpyxl Code Works:
load_workbook: Opens your existing Excel file.wb['Sheet1']: Selects the worksheet you want to work with.ws.columns: This gives you an iterable of all columns in the worksheet.get_column_letter: Converts a column number (like 1, 2, 3) into a letter ('A', 'B', 'C'). This is essential for setting the dimension.for cell in column: We loop through every cell in the current column to find the longest piece of text.str(cell.value): We convert the cell's value to a string to be able to measure its length. This handles numbers and dates correctly.ws.column_dimensions[column_letter].width = ...: This is the key line. It sets the width of the specified column.wb.save(): Saves the changes. Crucially, you must save the file for the changes to take effect.
Method 2: Using pandas (Great for DataFrames)
If your data is already in a pandas DataFrame (which is very common in data analysis), pandas can export it to an autofitted Excel file using openpyxl as an engine under the hood.
Step 1: Install pandas and openpyxl
pip install pandas openpyxl
Step 2: Exporting a DataFrame to an Autofitted Excel File
pandas doesn't have a direct autofit() method, but you can use the xlsxwriter engine for more control, or simply set the column widths based on the DataFrame's max string lengths before exporting.
Here's the most straightforward way:
import pandas as pd
# Sample DataFrame
data = {
'Product Name': ['A very long product name that needs space', 'Laptop', 'Mouse'],
'SKU': ['SKU-12345-ABC', 'SKU-67890-XYZ', 'SKU-54321-DEF'],
'Description': ['This is a detailed description of the product.', 'A portable computer.', 'An input device.'],
'Price': [999.99, 1200.50, 25.00]
}
df = pd.DataFrame(data)
# --- Create a Pandas Excel writer using the 'openpyxl' engine ---
# This allows us to use openpyxl features after writing the DataFrame.
writer = pd.ExcelWriter('pandas_output.xlsx', engine='openpyxl')
# --- Write the DataFrame to the Excel file ---
df.to_excel(writer, index=False, sheet_name='SalesData')
# --- Get the xlsxwriter workbook and worksheet objects ---
# This is the key to getting access to the underlying openpyxl objects.
workbook = writer.book
worksheet = writer.sheets['SalesData']
# --- Autofit the columns ---
# Iterate over the columns and set the width
for idx, col in enumerate(df.columns):
# Find the max length of the column and add some padding
max_len = max(df[col].astype(str).map(len).max(), len(col)) + 2
worksheet.column_dimensions[get_column_letter(idx + 1)].width = max_len
# --- Save the Excel file ---
writer.save()
print("DataFrame exported and columns autofitted using pandas.")
(Note: You'll need from openpyxl.utils import get_column_letter at the top of this script as well).

Important Considerations & Alternatives
Performance with openpyxl
The openpyxl method of looping through every cell can be very slow for large Excel files (e.g., >100,000 rows). For massive files, consider these options:
-
Set a Reasonable Max Width: Don't check every cell. Just check the first 100 or so rows. This is much faster and often good enough.
# Inside the column loop max_length = 0 # Check only the first 100 rows for performance for cell in column[:100]: # ... rest of the logic -
Use
xlsxwriterEngine: If you are creating a file from scratch (not modifying an existing one), thexlsxwriterengine is significantly faster.
Row Height Autofit
Autofitting rows is less common for text but can be useful for images or merged cells. The logic is similar to columns.
# After loading the workbook and worksheet with openpyxl...
# Loop through all rows
for row in ws.rows:
# Find the maximum height needed in this row
# This is a simplified example; calculating height based on font size is complex.
# A common approach is to set a fixed height if content overflows.
max_cell_height = 0
for cell in row:
# A simple heuristic: if the text is long, increase the row height
if cell.value and len(str(cell.value)) > 50:
max_cell_height = 30 # Set a fixed height
break
if max_cell_height > 0:
ws.row_dimensions[cell.row].height = max_cell_height
The XlsxWriter Engine (For New Files)
If you are generating a new Excel file and not modifying an existing one, xlsxwriter is often a better choice. It has a built-in set_column() method that is very efficient.
import pandas as pd
df = pd.DataFrame({'Very Long Column Header': ['data1', 'a much longer piece of data', 'short']})
# Use xlsxwriter engine
with pd.ExcelWriter('xlsxwriter_output.xlsx', engine='xlsxwriter') as writer:
df.to_excel(writer, sheet_name='Sheet1', index=False)
# Get the workbook and worksheet objects
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Get the dimensions of the DataFrame
(max_row, max_col) = df.shape
# Create a list of column headers
column_headers = [df.columns[i] for i in range(max_col)]
# Set the column widths
for i, col in enumerate(column_headers):
# Get the max length of the header and the data in the column
max_len = max(
df[col].astype(str).map(len).max(), # Max length of data
len(col) # Length of header
) + 2
worksheet.set_column(i, i, max_len) # Set column width (first_col, last_col, width)
print("File created with 