Skip to content

pandas and polars DataFrames

pandas and polars are optional. xlspy imports them lazily, only when you pass a DataFrame.

pip install "xlspy[pandas]"    # or: pip install "xlspy[polars]"

One-liners

import pandas as pd

from xlspy import to_xlsb, to_xlsx

df = pd.DataFrame(
    {
        "name": ["Alice", "Bob", "Cara"],
        "age": [25, 30, 41],
        "joined": pd.to_datetime(["2024-01-15", "2023-06-01", "2022-11-20"]),
    }
)

to_xlsx(df, "people.xlsx")
to_xlsb(df, "people.xlsb")
print("wrote people.xlsx and people.xlsb")

to_xlsx() and to_xlsb() create a workbook with one sheet named Sheet1. For more control, use a writer and write_dataframe().

Write into a sheet

import pandas as pd

from xlspy import F, Style, XlsxWriter

df = pd.DataFrame(
    {
        "product": ["Coffee", "Tea", "Juice"],
        "revenue": [12500, 8400, 5100],
        "joined": pd.to_datetime(["2024-01-15", "2023-06-01", "2022-11-20"]),
    }
)

with XlsxWriter("report.xlsx") as workbook:
    workbook.add_sheet("Data")
    workbook.write_dataframe(
        df,
        include_index=True,
        na_rep="n/a",
        formats={"revenue": F.THOUSANDS_SEP, "joined": F.DATE_ISO},
        header_style=Style(bold=True, fill="#1F4E78", font_color="#FFFFFF"),
        freeze_panes="A2",
    )
    workbook.add_sheet("Notes")
    workbook.write_sheet([["Generated by xlspy"]])

write_dataframe() behaves like write_sheet(): it accepts the same sheet options and writes into the last sheet added with add_sheet().

Options

Parameter Applies to Meaning
include_index pandas Prepend the index as leading column(s); MultiIndex is fully written. polars raises ValueError.
na_rep both Text for missing cells. Default is None, an empty cell.
formats both {column_name: format_string} using xlspy.F constants.

Type conversion

DataFrame value Written as
int, float, str, bool, Decimal native cell
pandas.Timestamp, datetime.datetime date/time cell
pandas.Timedelta, datetime.timedelta day fraction (Excel duration)
datetime.time, polars.Time day fraction
numpy scalars the Python value they hold
None, NaN, NaT, NA empty cell, or na_rep
MultiIndex columns levels joined with a space

NaN in plain rows

A NaN in a normal write_sheet() row raises ValueError, as does an infinite number. Use na_rep with DataFrames, or replace the value before writing.

polars

The API is identical:

import polars as pl
from xlspy import to_xlsb

df = pl.DataFrame({"name": ["Alice", "Bob"], "age": [25, 30]})
to_xlsb(df, "people.xlsb")

Next: Reading a workbook →