Export a Formatted Excel Report from pandas with xlsxwriter

Write a DataFrame to Excel with df.to_excel() and xlsxwriter, then format it: header styles, currency and percent formats, column widths, frozen panes, conditional formatting, Excel tables and an embedded Matplotlib chart.

To write a formatted Excel file from pandas, open pd.ExcelWriter("file.xlsx", engine="xlsxwriter"), call df.to_excel(writer, ...), and then format the sheet through writer.book and writer.sheets[...], which are the xlsxwriter objects underneath. df.to_excel() alone gives you values with no widths, formats or styling, so most of the work in a report is the few lines after it.

This post was run with pandas 3.1 and xlsxwriter 3.3. Install it with pip install xlsxwriter (openpyxl is used at the end only to check the file). To style a DataFrame for display in a notebook instead, see Style a pandas DataFrame.

Quick Example

The data is ten simulated products with units sold, revenue and margin (seeded, so the numbers match). The part to keep is everything inside the with block.

import numpy as np
import pandas as pd

rng = np.random.default_rng(21)
products = ["Kettle", "Toaster", "Blender", "Air fryer", "Mixer",
            "Grill", "Juicer", "Rice cooker", "Slow cooker", "Waffle iron"]
units = rng.integers(80, 900, len(products))
df = pd.DataFrame({
    "Product": products,
    "Units": units,
    "Revenue": (units * rng.uniform(18, 120, len(products))).round(2),
    "Margin": rng.uniform(0.08, 0.42, len(products)).round(3),
})

with pd.ExcelWriter("sales.xlsx", engine="xlsxwriter") as writer:
    df.to_excel(writer, sheet_name="Sales", index=False)
    book, sheet = writer.book, writer.sheets["Sales"]

    header = book.add_format({"bold": True, "font_color": "white", "bg_color": "#264653", "border": 1})
    for col, name in enumerate(df.columns):
        sheet.write(0, col, name, header)  # replaces the plain header pandas wrote

    sheet.set_column("A:A", 12)
    sheet.set_column("B:B", 7, book.add_format({"num_format": "#,##0"}))
    sheet.set_column("C:C", 13, book.add_format({"num_format": "$#,##0.00"}))
    sheet.set_column("D:D", 7, book.add_format({"num_format": "0.0%"}))
    sheet.freeze_panes(1, 0)                                  # keep the header visible
    sheet.autofilter(0, 0, len(df), len(df.columns) - 1)      # filter buttons

    total_row = len(df) + 1
    bold = book.add_format({"bold": True, "top": 1})
    money_bold = book.add_format({"bold": True, "top": 1, "num_format": "$#,##0.00"})
    sheet.write(total_row, 0, "Total", bold)
    sheet.write_formula(total_row, 2, f"=SUM(C2:C{total_row})", money_bold, df["Revenue"].sum())

Spreadsheet preview with a dark teal header row, product names, thousands-separated units, dollar revenue, percent margins and a bold total row

The numbers underneath stay numbers. Only the display changes, so Revenue is still a float that Excel can sum and sort, and it shows as $12,345.67. The Total row is a live SUM formula. The fourth argument to write_formula() is the value to show until Excel recalculates, which matters for viewers that never recalculate (previewers, some phone apps).

Three details are easy to miss. index=False stops pandas writing the row numbers as a first column. Cell formats passed to set_column() apply to the whole column, but a cell you write with its own format (like the header) keeps that one. And the with block saves the file when it exits, so there is no writer.save() (it was removed in pandas 2.0).

The preview image is a macOS Quick Look rendering of the workbook. It shows the cell formats, widths and header fill, and it does not draw conditional formats or inserted images, so those sections below describe the result and check the file in code instead.

How do I check what was written?

Read the file back with pandas to see the values, and with openpyxl to see the formatting. This is also how you test a report in a script, since nobody opens the workbook:

from openpyxl import load_workbook

print(pd.read_excel("sales.xlsx", nrows=3))  # nrows=3 skips the Total row

ws = load_workbook("sales.xlsx")["Sales"]
print(ws["C2"].number_format, ws["D2"].number_format, ws.freeze_panes, ws.auto_filter.ref)
   Product  Units   Revenue  Margin
0   Kettle    327  38599.96   0.318
1  Toaster    720  44054.88   0.155
2  Blender    396  11668.19   0.143
$#,##0.00 0.0% A2 A1:D11

A format string is the same one you would type under Format Cells > Custom in Excel: #,##0 for thousands separators, $#,##0.00 for currency, 0.0% for percent (the cell holds 0.275, Excel shows 27.5%) and yyyy-mm-dd for dates.

How do I add conditional formatting?

sheet.conditional_format(range, options) colors cells by their value, and Excel updates the colors when the numbers change. The range is a string like "D2:D11" or a tuple of row and column numbers. Here margin gets a three-color scale, units get data bars, and any revenue under $20,000 turns red:

with pd.ExcelWriter("sales-highlighted.xlsx", engine="xlsxwriter") as writer:
    df.to_excel(writer, sheet_name="Sales", index=False)
    book, sheet = writer.book, writer.sheets["Sales"]
    last = len(df) + 1

    sheet.conditional_format(f"D2:D{last}", {
        "type": "3_color_scale",
        "min_color": "#E76F51", "mid_color": "#FFFFFF", "max_color": "#2A9D8F",
    })
    sheet.conditional_format(f"B2:B{last}", {"type": "data_bar", "bar_color": "#8AB17D"})
    sheet.conditional_format(f"C2:C{last}", {
        "type": "cell", "criteria": "<", "value": 20000,
        "format": book.add_format({"font_color": "#C1121F", "bold": True}),
    })

check = load_workbook("sales-highlighted.xlsx")["Sales"].conditional_formatting
for rule_range in check:
    print(rule_range.sqref, [rule.type for rule in rule_range.rules])
low = df.loc[df["Revenue"] < 20000, "Product"].tolist()
print("under $20,000:", low)
D2:D11 ['colorScale']
B2:B11 ['dataBar']
C2:C11 ['cellIs']
under $20,000: ['Blender', 'Rice cooker', 'Slow cooker']

The "type" key takes "cell", "3_color_scale", "2_color_scale", "data_bar", "icon_set", "top", "formula" and more. Use "formula" with a criteria like =$D2<0.1 to color a whole row based on one column.

How do I turn the data into an Excel table?

An Excel table (Insert > Table) gives banded rows, filter buttons, a total row and structured references in one go. sheet.add_table() creates it, and you describe each column's format and total in the columns list. Write the table over the header pandas wrote by passing header=False and startrow=1 to to_excel(), so xlsxwriter owns the header cells:

with pd.ExcelWriter("sales-table.xlsx", engine="xlsxwriter") as writer:
    df.to_excel(writer, sheet_name="Sales", index=False, header=False, startrow=1)
    book, sheet = writer.book, writer.sheets["Sales"]

    money = book.add_format({"num_format": "$#,##0.00"})
    pct = book.add_format({"num_format": "0.0%"})
    sheet.add_table(0, 0, len(df) + 1, len(df.columns) - 1, {
        "name": "SalesTable",
        "style": "Table Style Medium 2",
        "total_row": True,
        "columns": [
            {"header": "Product", "total_string": "Total"},
            {"header": "Units", "total_function": "sum"},
            {"header": "Revenue", "format": money, "total_function": "sum"},
            {"header": "Margin", "format": pct, "total_function": "average"},
        ],
    })
    sheet.set_column("A:D", 14)

table = load_workbook("sales-table.xlsx")["Sales"].tables["SalesTable"]
print(table.ref, table.totalsRowCount)
A1:D12 1

add_table() ranges include the header and the total row, which is why the last row is len(df) + 1. The "columns" list must name every column, and its headers must match the cells you leave for the table to write. A total row of "average" for a percent column is the simple mean of the ten margins (it is not weighted by revenue), so use a formula if you need a weighted figure.

How do I put a Matplotlib chart in an Excel sheet?

xlsxwriter can draw native Excel charts, and for a chart type Excel does not have (a histogram with a fitted curve, a heatmap, an annotated chart) you draw it in Matplotlib and place the PNG on the sheet with sheet.insert_image(). Save at a high dpi so the picture stays sharp when someone zooms in:

import matplotlib.pyplot as plt

ordered = df.sort_values("Revenue")
fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
ax.barh(ordered["Product"], ordered["Revenue"] / 1000, color="#2A9D8F")
ax.axvline(df["Revenue"].mean() / 1000, color="#264653", linestyle="--", label="Mean")
ax.set_xlabel("Revenue ($k)")
ax.legend(loc="lower right")
fig.savefig("revenue-by-product.png", dpi=200)
plt.close(fig)

with pd.ExcelWriter("sales-report.xlsx", engine="xlsxwriter") as writer:
    df.to_excel(writer, sheet_name="Data", index=False)
    summary = writer.book.add_worksheet("Summary")
    summary.write("A1", "Revenue by product", writer.book.add_format({"bold": True, "font_size": 14}))
    summary.insert_image("A3", "revenue-by-product.png")

report = load_workbook("sales-report.xlsx")
print(report.sheetnames, "images on Summary:", len(report["Summary"]._images))  # openpyxl keeps loaded pictures here
['Data', 'Summary'] images on Summary: 1

Horizontal bar chart of revenue in thousands of dollars for ten products with a dashed line at the mean

insert_image() takes the top-left cell and an optional options dict. xlsxwriter reads the DPI stored in the PNG, so this 7-inch figure saved at dpi=200 (1400 pixels) is placed 672 pixels wide, its natural size on screen. Use {"x_scale": 0.5, "y_scale": 0.5} to shrink it, and object_position to choose whether the image moves with the cells. A picture is not linked to the data: if the numbers change, rerun the script to redraw it.

pandas ExcelWriter engines: xlsxwriter vs openpyxl

engine="xlsxwriter" engine="openpyxl"
Creates new files Yes Yes
Edits an existing workbook No Yes (mode="a")
Conditional formats, tables, data bars Full support Basic support
Number formats, widths, images Yes Yes
Reads .xlsx No (write only) Yes
Best for Building a polished report from scratch Adding a sheet to a file someone else made

Use xlsxwriter when the script owns the whole file. Use openpyxl when the file already exists, with pd.ExcelWriter("file.xlsx", engine="openpyxl", mode="a", if_sheet_exists="replace"). pd.read_excel() uses openpyxl for .xlsx files either way.

Practical Tips

  • Format after to_excel(), not before. pandas writes values with defaults. All formatting goes on the worksheet in the same with block, before it exits.
  • Dates need a format too. pandas writes datetimes with a default yyyy-mm-dd hh:mm:ss display. Pass datetime_format="yyyy-mm-dd" to pd.ExcelWriter to change it for every date column.
  • Set widths yourself. Excel does not auto-fit columns when a file is written by code. A quick estimate is df[col].astype(str).str.len().max() + 2.
  • Keep numbers as numbers. Don't format a column as strings like "$1,234" in pandas. Write the float and give it a number format, so the sheet still sorts and sums.
  • One workbook, several sheets. Call to_excel(writer, sheet_name=...) once per DataFrame inside the same with block.
  • Check the file in code. Reading it back with openpyxl, as above, catches a wrong range or a missing format without opening Excel.

Similar Topics