You could use set_column as follows:

worksheet1.set_column(1, 1, 25)

This is defined as follows:

set_column(first_col, last_col, width, cell_format, options)

You would need to determine a suitable width, perhaps based on the longest length of text in the whole column. Care though would be needed to base this on the font and size being used. Also consider if a proportional or fixed width font is used.

If you want to autofit all of the columns automatically regardless of the font and size, then you will need to use the win32com interface as follows:

import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r'file.xlsx')
ws = wb.Worksheets("Sheet1")
ws.Columns.AutoFit()
wb.Save()
excel.Application.Quit()

This can easily be done after you closed the file using your current xlsxwriter code. Note, you might need to supply a full path to your file.

Answer from Martin Evans on Stack Overflow
🌐
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.
Discussions

Worksheet.set_column() sets the column width only once
out = StringIO.StringIO() workbook = xlsxwriter.workbook.Workbook(out) worksheet = workbook.add_worksheet() worksheet.set_column('A:A', 1) worksheet.set_column('A:A', 100) workbook.close() out.seek(0) return out ... I don't think it's a LibreOffice issue this time, because the width is, in fact, ... More on github.com
🌐 github.com
15
December 18, 2013
excel - python xlsxwriter change all cell widths when using write_row - Stack Overflow
How would i define a column width for the entire 'worksheet' or for each column when using write_row()? For example i have: workbook = xlsxwriter.Workbook(loc_path + 'monbatch_test1.xlsx') worksh... More on stackoverflow.com
🌐 stackoverflow.com
December 6, 2016
Issue with set_column actual width different from set width
Hi, I am using XlsxWriter to do set the width to 8.5 but it appears to set it to 8.57. Setting 8.5x also sets it to 8.57. I am using Python version 3.7 and XlsxWriter 1.1.6 and Excel version 2013. ... More on github.com
🌐 github.com
6
April 12, 2019
Some notes on autofit()
Version 3.0.6 of XlsxWriter added a worksheet.autofit() function. The implementation is a technical compromise and I wanted to write some notes about it. First off let's start with the text that was in the FAQ: 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 ... More on github.com
🌐 github.com
12
January 4, 2023
🌐
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 the hood.
🌐
GitHub
github.com › jmcnamara › XlsxWriter › issues › 82
Worksheet.set_column() sets the column width only once · Issue #82 · jmcnamara/XlsxWriter
December 18, 2013 - out = StringIO.StringIO() workbook = xlsxwriter.workbook.Workbook(out) worksheet = workbook.add_worksheet() worksheet.set_column('A:A', 1) worksheet.set_column('A:A', 100) workbook.close() out.seek(0) return out · Expected outcome: Actual outcome: I don't think it's a LibreOffice issue this time, because the width is, in fact, set - but only once.
Author: jmcnamara
🌐
XlsxWriter
xlsxwriter.readthedocs.io › example_autofit.html
Example: Autofitting columns — XlsxWriter
##############################... 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 ...
🌐
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
Find elsewhere
🌐
GitHub
github.com › jmcnamara › XlsxWriter › issues › 622
Issue with set_column actual width different from set width · Issue #622 · jmcnamara/XlsxWriter
April 12, 2019 - Hi, I am using XlsxWriter to do set the width to 8.5 but it appears to set it to 8.57. Setting 8.5x also sets it to 8.57. I am using Python version 3.7 and XlsxWriter 1.1.6 and Excel version 2013. Here is some code that demonstrates the ...
Author: jmcnamara
🌐
Edureka Community
edureka.co › home › community › categories › others › adjust cell width in excel
Adjust cell width in Excel | Edureka Community
October 10, 2022 - I'm writing into an Excel sheet using xlsxwriter. The problem I'm having is that text that ... am getting What I am expecting with adjusted widths
🌐
Inwt-statistics
inwt-statistics.com › blog › automated-excel-reports-with-python
Automated Excel Reports with Python - INWT
January 26, 2022 - All other columns remain unchanged. :param sheet: object of class xlsxwriter.worksheet.Worksheet :param col_width_dict: dictionary with the columns widths where the keys are the column indices and the values are the column widths, e.g.
🌐
TutorialsPoint
tutorialspoint.com › python_xlsxwriter › python_xlsxwriter_quick_guide.htm
Python XlsxWriter - Quick Guide
The border itself can further be formatted by none, color, width and dash_type parameters. Line or border set to none means that the text box will not have any border. The dash_type parameter can be any of the following values − ... Here is a program that displays two text boxes, one with a solid border, red in color; and the second box has dash_dot type border in blue color. import xlsxwriter wb = xlsxwriter.Workbook('hello.xlsx') ws = wb.add_worksheet() ws.insert_textbox('B2', 'Welcome to Tutorialspoint', {'border': {'color': '#FF9900'}}) ws.insert_textbox('B10', 'Welcome to Tutorialspoint', { 'line': {'color': 'blue', 'dash_type': 'dash_dot'} }) wb.close()
🌐
GitHub
github.com › jmcnamara › XlsxWriter › issues › 936
Some notes on autofit() · Issue #936 · jmcnamara/XlsxWriter
January 4, 2023 - Anyway, with the current implementation XlsxWriter matches Excel's autofit for strings up to around 100 pixels (and there are a number of test_autofit??.py test cases that compare against Excel.
Author: jmcnamara
🌐
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 - Use pandas’ `to_excel` method to export the DataFrame as an Excel file, specifying XlsxWriter as the engine, and retrieve the worksheet object. Use the `set_column` method to set the column width, specifying the column range, the width value, and the cell format.
🌐
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. # # Note: THIS ISN'T A FULLY FUNCTIONAL AUTOFIT EXAMPLE. It is only a proof or # concept or a framework to try out solutions. # # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2013-2025, John McNamara, jmcnamara@cpan.org # from xlsxwriter.workbook import Workbook from xlsxwriter.worksheet import Worksheet, convert_cell_args def excel_string_width(string): """ Calculate the length of the string in Excel character units.
🌐
RubyDoc
rubydoc.info › gems › xlsxwriter › 0.0.3 › XlsxWriter › Worksheet
RubyDoc.info: Class: XlsxWriter::Worksheet – Documentation for xlsxwriter (0.0.3) – RubyDoc.info
Write a row. If no types passed XlsxWriter tries to deduce them automatically. Both types and style may be an array as well as a symbol. In the latter case they are applied to all cells in the row. height is a Numeric that specifies the row height. Apply cols automatic widths calculated by #add_row.
🌐
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 - The output of the above snippet is shown below. As we can see, the width of the column this_is_a_long_column_name has been adjusted to 20, while the remaining columns' width were adjusted to the default value which makes columns with longer width (such as the last one) to be cropped.
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:

🌐
XlsxWriter
xlsxwriter.readthedocs.io › example_tables.html
Example: Worksheet Tables — XlsxWriter
worksheet2.set_column("B:G", 12) # Write the caption. worksheet2.write("B1", caption) # Add a table to the worksheet. worksheet2.add_table("B3:F7", {"data": data}) ############################################################################### # # Example 3. # caption = "Table without default autofilter." # Set the columns widths.