# pandas and polars DataFrames

[Guide](<https://justybase.github.io/xlspy/usage/index.md>) · [Home](<https://justybase.github.io/xlspy/index.md>) · [Examples](<https://github.com/justybase/xlspy/blob/main/examples/README.md>)

## Writing pandas / polars DataFrames (optional)

`xlspy` can write a DataFrame directly to `.xlsx` or `.xlsb`. **pandas and polars are optional** — `xlspy` has no required dependencies and imports them lazily only when you actually pass a DataFrame:

```
pip install xlspy[pandas]   # pandas support
pip install xlspy[polars]   # polars support
```

The quickest way is the one-liner `to_xlsx` / `to_xlsb`:

```
import pandas as pd
from xlspy import to_xlsx, to_xlsb

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

to_xlsx(df, "people.xlsx")
to_xlsb(df, "people.xlsb")
```

The same works for polars, with an identical API:

```
import polars as pl
from xlspy import to_xlsb

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

For full control, use the writer method, which behaves exactly like `write_sheet` and writes into the last sheet added with `add_sheet`:

```
import pandas as pd
from xlspy import XlsxWriter, F

df = pd.DataFrame({
    "joined": pd.to_datetime(["2024-01-15", "2023-06-01"]),
    "age": [25, 30],
})

with XlsxWriter("report.xlsx") as writer:
    writer.add_sheet("Data")
    writer.write_dataframe(
        df,
        include_index=True,
        na_rep="n/a",
        formats={"joined": F.DATE_ISO, "age": F.THOUSANDS_SEP},
    )
    writer.add_sheet("Notes")
    writer.write_sheet([["Generated by xlspy"]])
```

## Reading into a DataFrame

`read_dataframe` streams a sheet into pandas or polars without building a list of rows first. It works for XLSX and XLSB, and for an already open `ExcelReader`:

```
from xlspy import read_dataframe

df = read_dataframe("report.xlsx", sheet_name="Sales")
frames = read_dataframe("report.xlsb", sheet_name=None)   # {name: DataFrame}
```

`header=True` uses the first row as column names, `header=False` generates `column_0`, `column_1`, ..., and a sequence supplies the names. `usecols`, `nrows` and `dtype` work like their pandas counterparts. Choose the engine with `engine="pandas"` or `engine="polars"`; `"auto"` prefers pandas. `ExcelReader` also has `to_pandas()` and `to_polars()`.

### Options

| Parameter | Applies to | Meaning |
| --- | --- | --- |
| `include_index` | pandas only | Prepend the index as leading column(s); all MultiIndex levels are written. polars has no index and raises `ValueError`. |
| `na_rep` | both | Text written for missing cells (`None` / `NaN` / `NaT` / `NA`). Default is `None`, i.e. an empty cell. |
| `formats` | both | `{column_name: format_string}` mapping, using the constants from `xlspy.F`. |

Values are converted to the types the writers understand:

| 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; apply `F.TIME_*` for display) |
| `datetime.time` (incl. `polars.Time`) | day fraction (apply `F.TIME_*` for display) |
| `numpy` scalars (`int64`, `float32`, `bool_`, ...) | native Python value (`.item()`) |
| `None`, `NaN`, `NaT`, `NA` | empty cell (or `na_rep`) |
| MultiIndex columns | flattened by joining the levels with a space |

Plain rows given to `write_sheet` follow the same rule for numpy integers, `bool_` and float16/float32 scalars: they are written as the Python value they hold (`int`, `bool` or `float`), so `float32(0.1)` is written as `0.10000000149011612`. A `NaN` among them raises `ValueError`, as a `float` NaN does.

See [`examples/dataframe_*.py`](<https://github.com/justybase/xlspy/blob/main/examples/>) and [`examples/polars_to_xlsx_xlsb.py`](<https://github.com/justybase/xlspy/blob/main/examples/polars_to_xlsx_xlsb.py>) for full, runnable scripts, indexed in [`examples/README.md`](<https://github.com/justybase/xlspy/blob/main/examples/README.md>).
