[NOTE: as of Jan 2023 xslxwriter added a new method called autofit. See jmcnamara's answer below]

As a general rule, you want the width of the columns a bit larger than the size of the longest string in the column. The with of 1 unit of the xlsxwriter columns is about equal to the width of one character. So, you can simulate autofit by setting each column to the max number of characters in that column.

Per example, I tend to use the code below when working with pandas dataframes and xlsxwriter.

It first finds the maximum width of the index, which is always the left column for a pandas to excel rendered dataframe. Then, it returns the maximum of all values and the column name for each of the remaining columns moving left to right.

It shouldn't be too difficult to adapt this code for whatever data you are using.

def get_col_widths(dataframe):
    # First we find the maximum length of the index column   
    idx_max = max([len(str(s)) for s in dataframe.index.values] + [len(str(dataframe.index.name))])
    # Then, we concatenate this to the max of the lengths of column name and its values for each column, left to right
    return [idx_max] + [max([len(str(s)) for s in dataframe[col].values] + [len(col)]) for col in dataframe.columns]

for i, width in enumerate(get_col_widths(dataframe)):
    worksheet.set_column(i, i, width)
Answer from Cole Diamond on Stack Overflow
🌐
XlsxWriter
xlsxwriter.readthedocs.io › example_autofit.html
Example: Autofitting columns — XlsxWriter
####################################################################### # # An example of using simulated autofit to automatically adjust the width of # worksheet columns based on the data in the cells. # # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2013-2025, John McNamara, jmcnamara@cpan.org # from xlsxwriter.workbook import Workbook workbook = Workbook("autofit.xlsx") worksheet = workbook.add_worksheet() # Write some worksheet data to demonstrate autofitting.
Top answer
1 of 12
92

[NOTE: as of Jan 2023 xslxwriter added a new method called autofit. See jmcnamara's answer below]

As a general rule, you want the width of the columns a bit larger than the size of the longest string in the column. The with of 1 unit of the xlsxwriter columns is about equal to the width of one character. So, you can simulate autofit by setting each column to the max number of characters in that column.

Per example, I tend to use the code below when working with pandas dataframes and xlsxwriter.

It first finds the maximum width of the index, which is always the left column for a pandas to excel rendered dataframe. Then, it returns the maximum of all values and the column name for each of the remaining columns moving left to right.

It shouldn't be too difficult to adapt this code for whatever data you are using.

def get_col_widths(dataframe):
    # First we find the maximum length of the index column   
    idx_max = max([len(str(s)) for s in dataframe.index.values] + [len(str(dataframe.index.name))])
    # Then, we concatenate this to the max of the lengths of column name and its values for each column, left to right
    return [idx_max] + [max([len(str(s)) for s in dataframe[col].values] + [len(col)]) for col in dataframe.columns]

for i, width in enumerate(get_col_widths(dataframe)):
    worksheet.set_column(i, i, width)
2 of 12
33

Update from January 2023.

XlsxWriter 3.0.6+ now supports a autofit() worksheet method:

from xlsxwriter.workbook import Workbook

workbook = Workbook('autofit.xlsx')
worksheet = workbook.add_worksheet()

# Write some worksheet data to demonstrate autofitting.
worksheet.write(0, 0, "Foo")
worksheet.write(1, 0, "Food")
worksheet.write(2, 0, "Foody")
worksheet.write(3, 0, "Froody")

worksheet.write(0, 1, 12345)
worksheet.write(1, 1, 12345678)
worksheet.write(2, 1, 12345)

worksheet.write(0, 2, "Some longer text")

worksheet.write(0, 3, "http://ww.google.com")
worksheet.write(1, 3, "https://github.com")

# Autofit the worksheet.
worksheet.autofit()

workbook.close()

Output:

Or using Pandas:

import pandas as pd

# Create a Pandas dataframe from some data.
df = pd.DataFrame({
    'Country':    ['China',    'India',    'United States', 'Indonesia'],
    'Population': [1404338840, 1366938189, 330267887,       269603400],
    'Rank':       [1,          2,          3,               4]})

# Order the columns if necessary.
df = df[['Rank', 'Country', 'Population']]

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_autofit.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)

# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']

worksheet.autofit()

# Close the Pandas Excel writer and output the Excel file.
writer.close()

Output:

🌐
GitHub
github.com › jmcnamara › XlsxWriter › issues › 936
Some notes on autofit() · Issue #936 · jmcnamara/XlsxWriter
January 4, 2023 - There is no "autofit" flag in the Excel XLSX format that will trigger the same autofit that you get from Excel at runtime. As a workaround I implemented a pixel calculation based on defined widths for all the characters in the ASCII range 32-126.
Author: jmcnamara
🌐
XlsxWriter
xlsxwriter.readthedocs.io › example_autofit_manually.html
Example: Autofitting columns manually — XlsxWriter
cities = ["Addis Ababa", "Buenos Aires", "Cairo", "Dhaka"] # Write the strings: worksheet.write_column(0, 0, cities) # Find the maximum column width in pixels. max_width = reduce(max, map(cell_autofit_width, cities)) # Set the column width as if it was auto-fitted.
🌐
XlsxWriter
xlsxwriter.readthedocs.io › worksheet.html
The Worksheet Class — XlsxWriter
Excel autofits columns at runtime ... formatting. XlsxWriter doesn’t have access to these Windows functions so it simulates autofit by calculating string widths based on metrics taken from Excel....
🌐
GitHub
github.com › jmcnamara › XlsxWriter › issues › 525
Autofit simulation example · Issue #525 · jmcnamara/XlsxWriter
May 17, 2018 - The following is a proof of concept on how to override the XlsxWriter write_string() method to track the longest string in a column so that it can be used to simulate autofit. Note, this is only a ...
Author: jmcnamara
🌐
XlsxWriter
xlsxwriter.readthedocs.io › changes.html
Changes in XlsxWriter - Read the Docs
Added the optional max_width parameter to the autofit() method to work around the issue where the autofit width is too big.
🌐
XlsxWriter
xlsxwriter.readthedocs.io › utility.html
Utility and Helper Functions - XlsxWriter - Read the Docs
The Worksheet autofit() method can be used to auto-fit cell data to the optimal column width.
🌐
XlsxWriter
xlsxwriter.readthedocs.io › example_inheritance2.html
Advanced example of subclassing - XlsxWriter - Read the Docs
In this example we see an approach to implementing a simulated autofit in a user application.
Find elsewhere
🌐
Libxlsxwriter
libxlsxwriter.github.io › faq.html
libxlsxwriter: Frequently Asked Questions
It is possible to simulate "AutoFit" by tracking the width of the data in the column as your write it.
🌐
GitHub
github.com › jmcnamara › XlsxWriter › issues › 323
AutoFit for worksheet.set_column · Issue #323 · jmcnamara/XlsxWriter
December 30, 2015 - I know there is no way to AutoFit column width like excel runtime, from PIL import ImageFont FONT = ImageFont.truetype('mingliu.ttc', size=17) (width,h) = FONT.getsize('test text') worksheet.set_column(0, 0, width*0.13953488372093023) th...
Author: jmcnamara
Top answer
1 of 3
13

Is there any possibility of setting the width of all columns automatically?

Unfortunately, not. From the XlsxWriter FAQ:

Q. Is there an "AutoFit" option for columns?

Unfortunately, there is no way to specify "AutoFit" for a column in the Excel file format. This feature is only available at runtime from within Excel. It is possible to simulate "AutoFit" in your application by tracking the maximum width of the data in the column as your write it and then adjusting the column width at the end.

Update from January 2023.

XlsxWriter 3.0.6+ now supports a autofit() worksheet method:

from xlsxwriter.workbook import Workbook

workbook = Workbook('autofit.xlsx')
worksheet = workbook.add_worksheet()

# Write some worksheet data to demonstrate autofitting.
worksheet.write(0, 0, "Foo")
worksheet.write(1, 0, "Food")
worksheet.write(2, 0, "Foody")
worksheet.write(3, 0, "Froody")

worksheet.write(0, 1, 12345)
worksheet.write(1, 1, 12345678)
worksheet.write(2, 1, 12345)

worksheet.write(0, 2, "Some longer text")

worksheet.write(0, 3, "http://ww.google.com")
worksheet.write(1, 3, "https://github.com")

# Autofit the worksheet.
worksheet.autofit()

workbook.close()

Output:

2 of 3
2

I only know of a way to do this with COM.

import contextlib, os, win32com.client

@contextlib.contextmanager
def load_xl_file(xlfilepath):
    ''' Open an existing Excel file using a context manager 
        `xlfilepath`: path to an existing Excel file '''
    xl = win32com.client.DispatchEx("Excel.Application")
    wb = xl.Workbooks.Open(xlfilepath)
    try:
        yield wb
    finally:
        wb.Close(SaveChanges=True)
        xl.Quit()
        xl = None # this actually ends the process 

def xlautofit(xlfilepath,skip_first_col=False):
    ''' relies on win32com.client to autofit columns on data sheets 

        remember that this is using COM so sheet numbers start at 1 (not 0), 
        so to avoid requiring the caller to remember this, we increment 

        returns full path (including dir) to file '''
    if os.path.splitext(xlfilepath)[1] not in ('.xls','.xlsx'):
        raise 
        return -1

    autofitbegcol = 1
    if skip_first_col:
        autofitbegcol += 1

    # Autofit every sheet 
    with load_xl_file(xlfilepath) as wb:
        for ws in wb.Sheets:
            autofitendcol = ws.UsedRange.Columns.Count
            ws.Range(ws.Cells(1, autofitbegcol), 
                     ws.Cells(1, autofitendcol)).EntireColumn.AutoFit()
    return xlfilepath 
🌐
GitHub
github.com › jmcnamara › XlsxWriter › issues › 1106
feature request: add max_width for autofit · Issue #1106 · jmcnamara/XlsxWriter
December 17, 2024 - # old worksheet.autofit() # new worksheet.autofit(100) # max width of 100 worksheet.autofit(300) # uses 255 as max width and outputs a warning
Author: jmcnamara
🌐
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 - Fortunately, pandas.ExcelWriter provides a way to adjust the column widths automatically based on the content of the cells. This can be achieved by using the set_column method of the XlsxWriter engine, which is used by pandas.ExcelWriter under ...
🌐
CSDN
devpress.csdn.net › python › 63044fc27e6682346619984e.html
Simulate autofit column in xslxwriter - DevPress官方社区- CSDN
August 23, 2022 - As a general rule, you want the ... columns is about equal to the width of one character. So, you can simulate autofit by setting each column to the max number of characters in that column....
🌐
GitHub
github.com › jmcnamara › XlsxWriter › issues › 1125
feature request: Adding support autofit in constant_memory mode · Issue #1125 · jmcnamara/XlsxWriter
March 26, 2025 - When I work with a large Excel file (more than 100k rows x 20 columns), I usually use constant_memory=True to keep the memory usage stable. However, this config disables the autofit feature. Then, I checked the source code and found a way to add support for it.
Author: jmcnamara
🌐
Rustxlsxwriter
rustxlsxwriter.github.io › examples › autofit.html
Autofitting columns - Working with the rust_xlsxwriter library
To get better results for autofitting numbers and dates you can enable the enhanced_autofit feature in your Cargo.toml file.
Starred by 3 users
Forked by 2 users
Languages: Python
🌐
GitHub
github.com › jmcnamara › XlsxWriter › issues › 203
AutoFit problem · Issue #203 · jmcnamara/XlsxWriter
December 22, 2014 - Hello Does anybody knows that how can I adjust the width of columns automatically?
Author: jmcnamara