[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
🌐
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. You can see that here and here. One of the main design goals of XlsxWriter is that it creates the exact same file format as Excel for the same input.
Author: jmcnamara
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 › 525
Autofit simulation example · Issue #525 · jmcnamara/XlsxWriter
May 17, 2018 - The actual autofit part doesn't work correctly. ####################################################################### # # Example of how to simulate autofit by overriding the write_string() # method to track the maximum width string in each column and then # set the column widths. # # Copyright 2013-2018, John McNamara, jmcnamara@cpan.org # import xlsxwriter from xlsxwriter.workbook import Workbook from xlsxwriter.worksheet import Worksheet from xlsxwriter.worksheet import convert_cell_args from xlsxwriter.compatibility import str_types def excel_string_width(str): """ Calculate the length of the string in Excel character units.
Author: jmcnamara
🌐
Libxlsxwriter
libxlsxwriter.github.io › faq.html
libxlsxwriter: Frequently Asked Questions
See Using vcpkg for Microsoft Visual Studio. All supported features are documented. In time the feature set may expand to include more of the functionality of the Python XlsxWriter module. Unfortunately, there is no way to specify "AutoFit" for a column in the Excel file format.
🌐
XlsxWriter
xlsxwriter.readthedocs.io › example_autofit.html
Example: Autofitting columns — XlsxWriter
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.
🌐
GitHub
github.com › jmcnamara › XlsxWriter › issues › 1145
Bug: autofit doesn't take format into account · Issue #1145 · jmcnamara/XlsxWriter
July 3, 2025 - Current behavior Autofit doesn't take format into account. As described here: https://xlsxwriter.readthedocs.io/worksheet.html#autofit [autofit] doesn’t take formatting of numbers or dates account, although this may be addressed in a lat...
Author: jmcnamara
🌐
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
🌐
XlsxWriter
xlsxwriter.readthedocs.io › example_inheritance2.html
Advanced example of subclassing - XlsxWriter - Read the Docs
This works by overriding the write_string() method to track the maximum width string in each column and then set the column widths when closing the workbook. ... This isn’t a fully functional autofit example (as shown by the longer strings in the screen shot).
🌐
GitHub
github.com › jmcnamara › XlsxWriter › issues › 1106
feature request: add max_width for autofit · Issue #1106 · jmcnamara/XlsxWriter
December 17, 2024 - When using the autofit method it'd be amazing if a maximum width for the columns could be specified instead of just the hardcoded 255. # 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
Find elsewhere
🌐
XlsxWriter
xlsxwriter.readthedocs.io › example_autofit_manually.html
Example: Autofitting columns manually — XlsxWriter
The worksheet ``autofit()`` # method will do this automatically but occasionally you may need to control the # maximum and minimum column widths yourself. # # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2013-2025, John McNamara, jmcnamara@cpan.org # from functools import reduce ...
🌐
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
🌐
XlsxWriter
xlsxwriter.readthedocs.io › utility.html
Utility and Helper Functions - XlsxWriter - Read the Docs
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. worksheet.set_column_pixels(0, 0, max_width) workbook.close() The limitations that apply to the Worksheet autofit method also applies to this function.
🌐
XlsxWriter
xlsxwriter.readthedocs.io › worksheet.html
The Worksheet Class — XlsxWriter
Excel autofits columns at runtime when it has access to all of the required worksheet information as well as the Windows functions for calculating display areas based on fonts and 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 › 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
🌐
GitHub
github.com › jmcnamara › libxlsxwriter › issues › 118
Question: Column Auto-Fit · Issue #118 · jmcnamara/libxlsxwriter
August 11, 2017 - I've read in the FAQ that this is not available here. But a hint for a workaround was given: It is possible to simulate "AutoFit" by tracking the width of the data in the column as yo...
Author: jmcnamara
🌐
CSDN
devpress.csdn.net › python › 63044fc27e6682346619984e.html
Simulate autofit column in xslxwriter - DevPress官方社区- CSDN
August 23, 2022 - Answer a question I would like to simulate the Excel autofit function in Python's xlsxwriter. According to this url, it is not directly supported: http://xlsxwriter.readthedocs.io/worksheet.html Howev Mangs Python
🌐
XlsxWriter
xlsxwriter.readthedocs.io › changes.html
Changes in XlsxWriter - Read the Docs
Add documentation and examples on Working with Polars and XlsxWriter to demonstrate new Polars integration of XlsxWriter in write_excel(). Add fix for rare issue with duplicate number formats. Fix for autofit() exception when user defined column width was None.
🌐
Stack Overflow
stackoverflow.com › questions › tagged › xlsxwriter
Highest scored 'xlsxwriter' questions - Stack Overflow
But, it is somewhat tricky to get many dataframes into one worksheet if you want to use ... python · excel · pandas · dataframe · xlsxwriter · nyan314sn · 2,006 asked Oct 5, 2015 at 20:35 · 76 votes · 12 answers · 131k views · I would like to simulate the Excel autofit function in Python's xlsxwriter. According to this url, it is not directly supported: http://xlsxwriter.readthedocs.io/worksheet.html However, it should be ...
🌐
DNMTechs
dnmtechs.com › simulating-autofit-column-in-xlsxwriter-with-python-3
Simulating Autofit Column in XlsxWriter with Python 3 – DNMTechs – Sharing and Storing Technology Knowledge
When working with spreadsheets in Python, one common requirement is to adjust the column widths so that the content fits neatly within each cell. This can be achieved using the autofit feature available in spreadsheet programs like Microsoft Excel. However, when using the popular XlsxWriter library in Python, there is no direct method to autofit columns.
🌐
GitHub
github.com › ChristianLemer › nu_plugin_xlsx › issues › 19
Try enhanced_autofit instead of reserving the date column width by hand · Issue #19 · ChristianLemer/nu_plugin_xlsx
1 week ago - rust_xlsxwriter 0.99 gained an enhanced_autofit feature, gated on a new ssfmt dependency. It sizes a column from the number format actually applied to a cell, which is precisely what plain autofit() cannot do. The plugin works around that blindness today.
Author: ChristianLemer