pandas
Excel
ExcelWriter
Python
data-analysis

Is there a way to auto-adjust Excel column widths with pandas.ExcelWriter?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Yes, but not as a built-in one-line pandas feature. pandas.ExcelWriter writes workbook data, while the visible column width is controlled by the underlying Excel engine. The standard solution is to estimate a reasonable width yourself and then apply it through XlsxWriter or openpyxl.

Why Pandas Does Not Do a True Autofit

Excel calculates visual width using font metrics, formatting, and GUI rendering details. Pandas does not run the Excel desktop application, so it cannot ask Excel to perform a real autofit in a portable way.

That is why the usual server-side strategy is only an approximation:

  • convert values to display text
  • measure the longest cell and header text
  • add a little padding
  • cap the width so one extreme value does not ruin the sheet

For most automated reports, that is good enough.

Use XlsxWriter to Set Widths

XlsxWriter is a common engine because it provides a direct set_column method.

python
1import pandas as pd
2
3
4def export_with_widths(df: pd.DataFrame, path: str, sheet_name: str = "Report") -> None:
5    with pd.ExcelWriter(path, engine="xlsxwriter") as writer:
6        df.to_excel(writer, index=False, sheet_name=sheet_name)
7        worksheet = writer.sheets[sheet_name]
8
9        for col_index, column_name in enumerate(df.columns):
10            values = df[column_name].fillna("").astype(str)
11            max_value_len = values.map(len).max() if not values.empty else 0
12            header_len = len(str(column_name))
13            width = min(max(max_value_len, header_len) + 2, 50)
14            worksheet.set_column(col_index, col_index, width)
15
16
17df = pd.DataFrame(
18    {
19        "name": ["Alice", "Bob", "Charlotte"],
20        "city": ["Toronto", "San Francisco", "Montreal"],
21        "department": ["Platform", "Data Engineering", "Operations"],
22    }
23)
24
25export_with_widths(df, "employees.xlsx")

This is the most common pandas pattern for “autofit-like” exports.

Do the Same Thing with openpyxl

If the workbook is already using openpyxl, the same idea works with a different API.

python
1import pandas as pd
2from openpyxl.utils import get_column_letter
3
4
5def export_with_widths_openpyxl(df: pd.DataFrame, path: str, sheet_name: str = "Report") -> None:
6    with pd.ExcelWriter(path, engine="openpyxl") as writer:
7        df.to_excel(writer, index=False, sheet_name=sheet_name)
8        worksheet = writer.sheets[sheet_name]
9
10        for index, column_name in enumerate(df.columns, start=1):
11            values = df[column_name].fillna("").astype(str)
12            max_value_len = values.map(len).max() if not values.empty else 0
13            header_len = len(str(column_name))
14            width = min(max(max_value_len, header_len) + 2, 50)
15            worksheet.column_dimensions[get_column_letter(index)].width = width

The principle is the same: pandas writes the data, then the engine adjusts layout settings.

Measure What Users Will Actually See

One subtle issue is that Excel shows formatted values, not raw Python objects. Dates, numbers, and nulls may appear differently once written.

That is why width estimation often starts with something like:

python
values = df[column_name].fillna("").astype(str)

If you later apply date or numeric formatting, you may need a little extra width beyond the raw string length estimate.

Add Padding and a Maximum Cap

A useful export is not just technically correct. It is readable.

If you never cap width, one very long cell can make the sheet awkward to use. If you never add padding, the content may look cramped. That is why examples usually use a formula like:

python
width = min(max(max_value_len, header_len) + 2, 50)

That balance is often more important than chasing pixel-perfect autofit behavior.

Common Pitfalls

The most common mistake is expecting to_excel() to auto-adjust widths by itself.

Another pitfall is measuring only the cell values and forgetting the header row. Developers also often let one unusually long value make the entire column absurdly wide when a simple maximum cap would keep the report readable.

Finally, remember that this is an approximation. Fonts, bold headers, wrapping, and merged cells can still make the result differ from interactive Excel autofit.

Summary

  • Pandas does not provide a true built-in universal Excel autofit.
  • The standard approach is to estimate widths and apply them through the writer engine.
  • 'XlsxWriter uses set_column, while openpyxl uses column_dimensions.'
  • Include both header and cell lengths in the width calculation.
  • Add padding and a maximum width cap so the exported workbook stays readable.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.