Inspired by user6178746's answer, I have the following:

# Given a dict of dataframes, for example:
# dfs = {'gadgets': df_gadgets, 'widgets': df_widgets}

writer = pd.ExcelWriter(filename, engine='xlsxwriter')
for sheetname, df in dfs.items():  # loop through `dict` of dataframes
    df.to_excel(writer, sheet_name=sheetname)  # send df to writer
    worksheet = writer.sheets[sheetname]  # pull worksheet object
    for idx, col in enumerate(df):  # loop through all columns
        series = df[col]
        max_len = max((
            series.astype(str).map(len).max(),  # len of largest item
            len(str(series.name))  # len of column name/header
            )) + 1  # adding a little extra space
        worksheet.set_column(idx, idx, max_len)  # set column width
writer.save()
Answer from alichaudry on Stack Overflow
Top answer
1 of 16
135

Inspired by user6178746's answer, I have the following:

# Given a dict of dataframes, for example:
# dfs = {'gadgets': df_gadgets, 'widgets': df_widgets}

writer = pd.ExcelWriter(filename, engine='xlsxwriter')
for sheetname, df in dfs.items():  # loop through `dict` of dataframes
    df.to_excel(writer, sheet_name=sheetname)  # send df to writer
    worksheet = writer.sheets[sheetname]  # pull worksheet object
    for idx, col in enumerate(df):  # loop through all columns
        series = df[col]
        max_len = max((
            series.astype(str).map(len).max(),  # len of largest item
            len(str(series.name))  # len of column name/header
            )) + 1  # adding a little extra space
        worksheet.set_column(idx, idx, max_len)  # set column width
writer.save()
2 of 16
81

Dynamically adjust all the column lengths

writer = pd.ExcelWriter('/path/to/output/file.xlsx') 
df.to_excel(writer, sheet_name='sheetName', index=False, na_rep='NaN')

for column in df:
    column_length = max(df[column].astype(str).map(len).max(), len(column))
    col_idx = df.columns.get_loc(column)
    writer.sheets['sheetName'].set_column(col_idx, col_idx, column_length)

writer.close()  # (writer.save() was deprecated and removed as of 2023/2024)

Manually adjust a column using Column Name

col_idx = df.columns.get_loc('columnName')
writer.sheets['sheetName'].set_column(col_idx, col_idx, 15)

Manually adjust a column using Column Index

writer.sheets['sheetName'].set_column(col_idx, col_idx, 15)

In case any of the above is failing with

AttributeError: 'Worksheet' object has no attribute 'set_column'

make sure to install xlsxwriter:

pip install xlsxwriter

and use it as the engine:

writer = pd.ExcelWriter('/path/to/output/file.xlsx', engine='xlsxwriter') 

For a more comprehensive explanation you can read the article How to Auto-Adjust the Width of Excel Columns with Pandas ExcelWriter on TDS.

🌐
Medium
medium.com › @tubelwj › two-methods-to-automatically-adjust-column-width-in-excel-when-exporting-from-pandas-0a228d64e8b3
Two methods to automatically adjust column width in Excel when exporting from pandas | by Gen. Devin DL. | Medium
October 2, 2024 - Iterate through all the columns of the worksheet, use the `column_dimensions` property to get the column object, and set the `auto_size` property to `True`, indicating automatic adjustment of column width.
Discussions

python - Writing Pandas DataFrame to Excel: How to auto-adjust column widths - Stack Overflow
I am trying to write a series of pandas DataFrames to an Excel worksheet such that: The existing contents of the worksheet are not overwritten or erased, and the Excel column widths are adjusted t... More on stackoverflow.com
🌐 stackoverflow.com
python 3.x - Export pandas dataframe to Excel and setting columns width and text wrapping - Stack Overflow
import pandas as pd import xlsxwriter ... df2.to_excel(writer, sheet_name='Sheet_name_2') I know that 'xlsxwriter' allows multiple customizations. How to set column width and text wrapping, taking the above code as the draft? ... See the docs on Working with Python Pandas and XlsxWriter ... More on stackoverflow.com
🌐 stackoverflow.com
A way to auto-adjust column widths when using pd.ExcelWriter?
Reference to this StackOverflow question: http://stackoverflow.com/questions/17326973/is-there-a-way-to-auto-adjust-excel-column-widths-with-pandas-excelwriter It would be a nice feature to have th... More on github.com
🌐 github.com
15
June 26, 2013
Excel column width
https://medium.com/@tubelwj/two-methods-to-automatically-adjust-column-width-in-excel-when-exporting-from-pandas-0a228d64e8b3 More on reddit.com
🌐 r/learnpython
8
1
May 2, 2025
🌐
XlsxWriter
xlsxwriter.readthedocs.io › example_pandas_column_formats.html
Example: Pandas Excel output with column formatting — XlsxWriter
An example of converting a Pandas dataframe to an Excel file with column formats using Pandas and XlsxWriter.
🌐
TechOverflow
techoverflow.net › 2021 › 03 › 05 › how-to-auto-fit-pandas-pd-to_excel-xlsx-column-width
How to auto-fit Pandas pd.to_excel() XLSX column width | TechOverflow
December 22, 2025 - # Load example dataset df = pd.read_csv("https://datasets.techoverflow.net/timeseries-example.csv", parse_dates=["Timestamp"]) df.set_index("Timestamp", inplace=True) # Export dataset to XLSX with pd.ExcelWriter("example.xlsx") as writer: df.to_excel(writer, sheet_name="MySheet") auto_adjust_xlsx_column_width(df, writer, sheet_name="MySheet", margin=0) Note that the algorithm currently tends to oversize the columns a bit, but in most cases, every type of column will fit. Check out similar posts by category: Pandas, Python ·
🌐
Towards Data Science
towardsdatascience.com › home › latest › how to auto-adjust the width of excel columns with pandas excelwriter
How to Auto-Adjust the Width of Excel Columns with Pandas ExcelWriter | Towards Data Science
March 5, 2025 - All columns are adjusted to the corresponding width that will make them fit into the space without being cropped. Output pandas DataFrame into Excel spreadsheet with auto-adjusted columns’ width
🌐
Saturn Cloud
saturncloud.io › blog › is-there-a-way-to-autoadjust-excel-column-widths-with-pandasexcelwriter
Is there a way to autoadjust Excel column widths with pandas ExcelWriter | Saturn Cloud Blog
May 1, 2026 - When exporting a pandas data frame to Excel using pandas.ExcelWriter, the default column widths may not be optimal for displaying the data. In fact, the columns may be too narrow, causing the data to be truncated, or too wide, wasting valuable screen space.
Top answer
1 of 3
6

Try to use this helper function (updated version):


Old version, which is no longer compatible with Pandas 1.3.0+:

import numpy as np
import pandas as pd
from pathlib import Path
from typing import Union, Optional, List, Tuple
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter


def append_df_to_excel(
        filename: Union[str, Path],
        df: pd.DataFrame,
        sheet_name: str = 'Sheet1',
        startrow: int = None,
        max_col_width: int = 40,
        autofilter: bool = False,
        fmt_int: str = "#,##0",
        fmt_float: str = "#,##0.00",
        fmt_date: str = "yyyy-mm-dd",
        fmt_datetime: str = "yyyy-mm-dd hh:mm",
        truncate_sheet: bool = False,
        **to_excel_kwargs
) -> None:
    """
    Append a DataFrame [df] to existing Excel file [filename]
    into [sheet_name] Sheet.
    If [filename] doesn't exist, then this function will create it.

    @param filename: File path or existing ExcelWriter
                     (Example: '/path/to/file.xlsx')
    @param df: DataFrame to save to workbook
    @param sheet_name: Name of sheet which will contain DataFrame.
                       (default: 'Sheet1')
    @param startrow: upper left cell row to dump data frame.
                     Per default (startrow=None) calculate the last row
                     in the existing DF and write to the next row...
    @param max_col_width: maximum column width in Excel. Default: 30
    @param autofilter: boolean - whether add Excel autofilter or not. Default: True
    @param fmt_int: Excel format for integer numbers
    @param fmt_float: Excel format for float numbers
    @param fmt_date: Excel format for dates
    @param fmt_datetime: Excel format for datetime's
    @param truncate_sheet: truncate (remove and recreate) [sheet_name]
                           before writing DataFrame to Excel file
    @param to_excel_kwargs: arguments which will be passed to `DataFrame.to_excel()`
                            [can be a dictionary]
    @return: None

    Usage examples:

    >>> append_df_to_excel('d:/temp/test.xlsx', df, autofilter=True,
                           freeze_panes=(1,0))

    >>> append_df_to_excel('d:/temp/test.xlsx', df, header=None, index=False)

    >>> append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2',
                           index=False)

    >>> append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2',
                           index=False, startrow=25)

    >>> append_df_to_excel('d:/temp/test.xlsx', df, index=False,
                           fmt_datetime="dd.mm.yyyy hh:mm")

    (c) MaxU
    """
    def set_column_format(ws, column_letter, fmt):
        for cell in ws[column_letter]:
            cell.number_format = fmt
    filename = Path(filename)
    file_exists = filename.is_file()
    # process parameters
    first_col = int(to_excel_kwargs.get("index", True)) + 1
    sheet_name = to_excel_kwargs.get("sheet_name", "Sheet1")
    # ignore [engine] parameter if it was passed
    if 'engine' in to_excel_kwargs:
        to_excel_kwargs.pop('engine')

    with pd.ExcelWriter(
        filename.with_suffix(".xlsx"),
        engine="openpyxl",
        mode="a" if file_exists else "w",
        date_format=fmt_date,
        datetime_format=fmt_datetime,
        **to_excel_kwargs
    ) as writer:
        if file_exists:
            # try to open an existing workbook
            writer.book = load_workbook(filename)
            # get the last row in the existing Excel sheet
            # if it was not specified explicitly
            if startrow is None and sheet_name in writer.book.sheetnames:
                startrow = writer.book[sheet_name].max_row
            # truncate sheet
            if truncate_sheet and sheet_name in writer.book.sheetnames:
                # index of [sheet_name] sheet
                idx = writer.book.sheetnames.index(sheet_name)
                # remove [sheet_name]
                writer.book.remove(writer.book.worksheets[idx])
                # create an empty sheet [sheet_name] using old index
                writer.book.create_sheet(sheet_name, idx)

            # copy existing sheets
            writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
        else:
            # file doesn't exist, we are creating a new one
            startrow = 0

        # write out the DataFrame to an ExcelWriter
        df.to_excel(writer, sheet_name=sheet_name, startrow=startrow,
                    **to_excel_kwargs)

        # automatically set columns' width
        worksheet = writer.sheets[sheet_name]
        for xl_col_no, dtyp in enumerate(df.dtypes, first_col):
            col_no = xl_col_no - first_col
            width = max(df.iloc[:, col_no].astype(str).str.len().max(),
                        len(df.columns[col_no]) + 6)
            width = min(max_col_width, width)
            # print(f"column: [{df.columns[col_no]} ({dtyp.name})]\twidth:\t[{width}]")
            column_letter = get_column_letter(xl_col_no)
            worksheet.column_dimensions[column_letter].width = width
            if np.issubdtype(dtyp, np.integer):
                set_column_format(worksheet, column_letter, fmt_int)
            if np.issubdtype(dtyp, np.floating):
                set_column_format(worksheet, column_letter, fmt_float)
        if autofilter:
            worksheet.auto_filter.ref = worksheet.dimensions

2 of 3
2

You can also try using the openpyxl bestFit attribute, which sets the column width to the same width that double clicking on the border of the column does. It should do the trick. Try doing something like this:

for column in df:
    ws.column_dimensions[column].bestFit = True

Depending on why you're exporting to Excel, you could also look into a number of different Python based spreadsheets. I'm the author of one called Mito. It lets you display your pandas dataframe as an interactive spreadsheet.

Find elsewhere
🌐
YouTube
youtube.com › pygpt
python pandas excel column width - YouTube
Instantly Download or Run the code at https://codegive.com title: python pandas tutorial: adjusting excel column width with code examplesintroduction:in dat...
Published   February 17, 2024
Views   31
🌐
GitHub
github.com › pandas-dev › pandas › issues › 4049
A way to auto-adjust column widths when using pd.ExcelWriter? · Issue #4049 · pandas-dev/pandas
June 26, 2013 - EnhancementIO Excelread_excel, to_excelread_excel, to_excelOutput-Formatting__repr__ of pandas objects, to_string__repr__ of pandas objects, to_string ... Reference to this StackOverflow question: http://stackoverflow.com/questions/17326973/is-there-a-way-to-auto-adjust-excel-column-widths-with-pandas-excelwriter
Author   pandas-dev
🌐
Reddit
reddit.com › r/learnpython › excel column width
r/learnpython on Reddit: Excel column width
May 2, 2025 -

I have a script which essentially creates a new excel doc based off of other excel documents. I finally use pd.to_excel to save this but the document has terrible column widths. I want to adjust them so they are the right size.

Someone suggested creating a template excel document and having the script paste the data frame in there and save. Someone else told me I can set the column widths.

I am only using pandas and I want a new doc saved each day with a different date which is what currently happens.

Any help?

🌐
Inwt-statistics
inwt-statistics.com › blog › automated-excel-reports-with-python
Automated Excel Reports with Python - INWT
January 26, 2022 - The first part of the article describes the most important functions and actions, for example, setting column widths, changing font colors, or adding hyperlinks to other sheets. In the second part, all of these features are combined in one Excel file. If you're looking for a template for python to excel reporting, take a look at our public GitHub repository python-excel-report. In this section, you will learn how to write a pandas data frame to an Excel file, change the sheet name and adapt column widths.
🌐
Ojdo
ojdo.de › wp › 2019 › 10 › pandas-to-excel-with-openpyxl
How to create a nicely formatted Excel table from a pandas DataFrame using openpyxl – ojdo
October 10, 2019 - On my machine, the resulting worksheets has a column width of 20.29… · with pd.ExcelWriter( output_filename, mode='a', # append; default='w' (overwrite) engine='openpyxl') as xlsx: sheet_name = 'Little customization' df.to_excel(xlsx, sheet_name) # set index column width ws = xlsx.sheets[sheet_name] ws.column_dimensions['A'].width = 21
🌐
YouTube
youtube.com › watch
Is there a way to auto-adjust Excel column widths with pandas ...
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
Published   February 12, 2022
🌐
YouTube
youtube.com › watch
Setting Your Column Widths in xlsxwriter - YouTube
In xlsxwriter, you can use the set_column() function to define column widths when converting from Python to Excel..set_column() needs two parameters to achie...
Published   October 14, 2017
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 1.1 › reference › api › pandas.DataFrame.to_excel.html
pandas.DataFrame.to_excel — pandas 1.1.5 documentation
DataFrame.to_excel(excel_writer, sheet_name='Sheet1', na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, startrow=0, startcol=0, engine=None, merge_cells=True, encoding=None, inf_rep='inf', verbose=True, freeze_panes=None)[source]¶
🌐
Velog
velog.io › @sacross93 › Enhance-Your-Pandas-Excel-Output-Freezing-Panes-Filtering-and-Adjusting-Column-Widths
Enhance Your Pandas Excel Output: Freezing Panes, Filtering, and Adjusting Column Widths
import pandas as pd # Assuming ... # Adjust column width for each column for i, col in enumerate(df.columns): width = get_width(col) # Custom function to calculate width based on column content ws.set_column(i, i, width ...
🌐
Python.org
discuss.python.org › python help
With Pandas, how do I set the column width by column number? - Python Help - Discussions on Python.org
April 8, 2024 - Python 3.12 on Windows 10 Pro. I think I understand using pandas with xlsxwriter, but I am having a hard time finding any pages that set the column width by column number. For example I want to set the column width of column 0 to 25 (in whatever units Excel uses). Why do I want to do this?
🌐
YouTube
youtube.com › logicgpt
pandas export to excel column width - YouTube
Download this code from https://codegive.com Sure thing! Here's a step-by-step tutorial on how to export a Pandas DataFrame to an Excel file while customizin...
Published   January 11, 2024
Views   20