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 OverflowYou 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.
Unfortunately xlsxwriter doesnt provide autofit option.
You can however track the largest entry for each column and then set the column width in the end with set column command.
set_column(first_col, last_col, width, cell_format, options)
In your case for instance, you should set the width of B column to the length of the largest string.
width= len("long text hidden test-1")
worksheet1.set_column(1, 1, width)
Worksheet.set_column() sets the column width only once
excel - python xlsxwriter change all cell widths when using write_row - Stack Overflow
Issue with set_column actual width different from set width
Some notes on autofit()
There is a relevant set_column() method that accept width:
set_column(first_col, last_col, width, cell_format, options)
Set properties for one or more columns of cells.
Here is how you can apply it:
worksheet.set_column(0, 2, 100)
The solution would be
def compute_rows(text, width):
if len(text) < width:
return 1
phrases = text.replace('\r', '').split('\n')
rows = 0
for phrase in phrases:
if len(phrase) < width:
rows = rows + 1
else:
words = phrase.split(' ')
temp = ''
for idx, word in enumerate(words):
temp = temp + word + ' '
# check if column width exceeded
if len(temp) > width:
rows = rows + 1
temp = '' + word + ' '
# check if it is not the last word
if idx == len(words) - 1 and len(temp) > 0:
rows = rows + 1
return rows
But you can see it in details here: http://assist-software.net/blog/how-export-excel-files-python-django-application
[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)
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:
