# Writing

New workbooks: the writers, sheet options and DataFrame export.

[API reference](<https://justybase.github.io/xlspy/api/index.md>) · [Guide](<https://justybase.github.io/xlspy/usage/index.md>)

## XlsxWriter

```
XlsxWriter(file: WriteTarget, compression_level: int = 3, use_shared_strings: bool = True, spool_max_bytes: int = DEFAULT_SPOOL_BYTES, strings_to_formulas: bool = False, strings_to_numbers: bool = False, strings_to_urls: bool = False, nan_inf_to_errors: bool = False, **unknown: object)
```

Bases: `_XlsxSheetMixin`, `_XlsxStylesMixin`, `_XlsxPartsMixin`, `_XlsxSheetXmlMixin`, `WriterFrontEnd`, `StagedWriter`, `DocumentPropertiesMixin`

Write XLSX workbooks with a row-oriented API.

A writer collects sheets, styles, tables, charts and other objects, then publishes the package when the `with` block exits. Rows are consumed once, so a generator or a database cursor can be passed straight to `write_sheet`.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `file` | `WriteTarget` | A path or a binary file object to write. | *required* |
| `compression_level` | `int` | ZIP compression level, 0-9 (default 3). | `3` |
| `use_shared_strings` | `bool` | Store every distinct string once (default). Set it to `False` for high-cardinality exports. | `True` |
| `spool_max_bytes` | `int` | Bytes kept in memory before sheet rows spill to a temporary file. | `DEFAULT_SPOOL_BYTES` |

Examples:

Write a styled report and read it back:

```
from xlspy import ExcelReader, F, Style, XlsxWriter

with XlsxWriter("report.xlsx") as workbook:
    workbook.add_sheet("Sales")
    workbook.write_sheet(
        [["Product", "Revenue"], ["Coffee", (12500, F.THOUSANDS_SEP)]],
        header_style=Style(bold=True, fill="183C52", font_color="FFFFFF"),
        freeze_panes="A2",
    )

with ExcelReader("report.xlsx") as reader:
    print(reader.read_all("Sales"))
```

**See Also**

`XlsbWriter` for the binary XLSB format with the same API, and `to_xlsx` for a DataFrame one-liner.

### add\_vba\_project

```
add_vba_project(project: str | PathLike[str] | bytes | bytearray | memoryview | Any) -> None
```

Embed a VBA project (`vbaProject.bin`) in the workbook.

The package becomes macro-enabled, so save it with an `.xlsm` (or `.xltm`) extension. `project` may be a path, bytes or a binary file object. Call `set_vba_name` to set the project's code name.

### set\_vba\_name

```
set_vba_name(name: str) -> None
```

Set the workbook code name (`workbookPr/@codeName`) for the VBA project.

### set\_defined\_name

```
set_defined_name(definition: DefinedName) -> None
```

Set a global or worksheet-local name; local titles are checked on save.

### get\_defined\_names

```
get_defined_names() -> list[DefinedName]
```

The defined names set so far.

### remove\_defined\_name

```
remove_defined_name(name: str, scope: str | None = None) -> None
```

Remove a defined name; with `scope`, the one local to that sheet.

### set\_properties

```
set_properties(*, title: str | None = None, subject: str | None = None, author: str | None = None, manager: str | None = None, company: str | None = None, category: str | None = None, keywords: str | None = None, comments: str | None = None, status: str | None = None, created: datetime | None = None, custom: dict | None = None) -> None
```

Set the document properties shown in Excel under File \> Info.

Text fields are optional strings. `created` defaults to the time of the call; a naive datetime is taken as UTC. `custom` maps property names to str, int, float, bool, date or datetime values and appears under File \> Info \> Properties \> Advanced Properties \> Custom. Calling it again replaces every earlier value.

### set\_workbook\_protection

```
set_workbook_protection(protection: WorkbookProtection) -> None
```

Lock the workbook structure, with a password when one is given.

### save

```
save() -> None
```

Write the workbook parts. The file is published when the writer closes.

### close

```
close() -> None
```

Close the writer, publishing the workbook if `save()` succeeded.

### write\_sheet

```
write_sheet(data: Iterable[list[Any]], *, options: SheetOptions | None = None, **kwargs: Any) -> None
```

Write rows to the current sheet.

`data` is consumed once, row by row. Sheet settings come from `options` (a `SheetOptions`) or from keyword arguments with the same names; a keyword argument overrides the matching field of `options`. The rows are encoded into a temporary spool (kept in memory up to `spool_max_bytes`, then on disk), so memory does not grow with the number of rows. Hyperlinks, formulas and the other options are described in the documentation.

### write\_dataframe

```
write_dataframe(df: Any, include_index: bool = False, na_rep: Any = None, formats: dict | None = None, *, header_style: Style | None = None, styles: dict[str, Style] | None = None, merges: list[str] | tuple[str, ...] | None = None, conditional_formats: list | tuple | None = None, tables: list[ExcelTable] | tuple[ExcelTable, ...] | None = None, column_widths: dict | None = None, autofit_rows: int | None = 1000, autofit_padding: float = 0.0, hidden_columns: list | tuple | set | None = None, row_heights: dict | None = None, hidden_rows: list | tuple | set | None = None, row_groups: list | tuple | None = None, column_groups: list | tuple | None = None, freeze_panes: str | None = None, auto_filter: bool | None = None, charts: list | tuple | None = None, data_validations: list | tuple | None = None, images: list | tuple | None = None, print_settings: PrintSettings | None = None, comments: Mapping[str, Comment] | None = None, threaded_comments: Mapping[str, Any] | None = None, sheet_protection: SheetProtection | None = None, show_grid_lines: bool = True, tab_color: Color | str | None = None, zoom: int | None = None, show_row_col_headers: bool = True, show_zero_values: bool = True, right_to_left: bool = False, pivots: list | tuple | None = None) -> None
```

Write a pandas or polars DataFrame to the current sheet.

pandas and polars are optional: they are imported lazily only when a DataFrame is actually passed in.

##### Parameters

df: A `pandas.DataFrame` or `polars.DataFrame`. include\_index: pandas only -- prepend the index as leading column(s). na\_rep: Value for missing cells, defaults to `None` (empty cell). formats: Optional `{column_name: format_string}` mapping (see `xlspy.F`).

## XlsbWriter

```
XlsbWriter(file: WriteTarget, compression_level: int = 3, use_shared_strings: bool = True, strings_to_formulas: bool = False, strings_to_numbers: bool = False, strings_to_urls: bool = False, nan_inf_to_errors: bool = False, **unknown: object)
```

Bases: `_XlsbStylesMixin`, `_XlsbPartsMixin`, `_XlsbSheetMixin`, `_XlsbViewsMixin`, `_XlsbBinMixin`, `_XlsbStringsMixin`, `WriterFrontEnd`, `StagedWriter`, `XlsbWriterMetadata`, `DocumentPropertiesMixin`

Write XLSB workbooks with the same API as `XlsxWriter`.

XLSB is Excel's binary workbook format. It is faster and smaller than XLSX for large exports, at the cost of narrower support in third-party readers. Rows are consumed once and encoded as they are produced, so memory does not grow with the number of rows.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `file` | `WriteTarget` | A path or a binary file object to write. | *required* |
| `compression_level` | `int` | ZIP compression level, 0-9 (default 3). | `3` |
| `use_shared_strings` | `bool` | Store every distinct string once (default). Set it to `False` to store text inline and bound memory on high-cardinality exports. | `True` |

Examples:

Write the same report as XLSB:

```
from xlspy import F, Style, XlsbWriter

with XlsbWriter("report.xlsb") as workbook:
    workbook.add_sheet("Sales")
    workbook.write_sheet(
        [["Product", "Revenue"], ["Coffee", (12500, F.THOUSANDS_SEP)]],
        header_style=Style(bold=True, fill="183C52", font_color="FFFFFF"),
        freeze_panes="A2",
    )
```

Stream a million rows from a generator with bounded memory:

```
from xlspy import XlsbWriter

def rows(count):
    for i in range(count):
        yield [i, f"row-{i}", i * 1.5]

with XlsbWriter("large.xlsb", use_shared_strings=False) as workbook:
    workbook.add_sheet("Data")
    workbook.write_sheet(rows(1_000_000))
```

**See Also**

`XlsxWriter` for maximum compatibility, and `to_xlsb` for a DataFrame one-liner. XLSB formulas use a binary grammar; an unsupported token raises `UnsupportedFeatureError` instead of writing a broken file.

### set\_properties

```
set_properties(*, title: str | None = None, subject: str | None = None, author: str | None = None, manager: str | None = None, company: str | None = None, category: str | None = None, keywords: str | None = None, comments: str | None = None, status: str | None = None, created: datetime | None = None, custom: dict | None = None) -> None
```

Set the document properties shown in Excel under File \> Info.

Text fields are optional strings. `created` defaults to the time of the call; a naive datetime is taken as UTC. `custom` maps property names to str, int, float, bool, date or datetime values and appears under File \> Info \> Properties \> Advanced Properties \> Custom. Calling it again replaces every earlier value.

### add\_sheet

```
add_sheet(sheet_name: str, hidden: bool = False) -> None
```

Start a new sheet; the next `write_sheet` call fills it.

`hidden=True` hides the sheet.

### set\_defined\_name

```
set_defined_name(definition: DefinedName) -> None
```

Add a defined name, replacing one with the same name and scope.

### get\_defined\_names

```
get_defined_names() -> list[DefinedName]
```

The defined names set so far.

### remove\_defined\_name

```
remove_defined_name(name: str, scope: str | None = None) -> None
```

Remove a defined name; with `scope`, the one local to that sheet.

### set\_workbook\_protection

```
set_workbook_protection(protection: WorkbookProtection) -> None
```

Lock the workbook structure, with a password when one is given.

### save

```
save() -> None
```

Write the workbook parts. The file is published when the writer closes.

### close

```
close() -> None
```

Close the writer, publishing the workbook if `save()` succeeded.

### write\_sheet

```
write_sheet(data: Iterable[list[Any]], *, options: SheetOptions | None = None, **kwargs: Any) -> None
```

Write rows to the current sheet.

Sheet settings come from `options` (a `SheetOptions`) or from keyword arguments with the same names; a keyword argument overrides the matching field of `options`.

### write\_dataframe

```
write_dataframe(df: Any, include_index: bool = False, na_rep: Any = None, formats: dict | None = None, *, header_style: Style | None = None, styles: dict[str, Style] | None = None, merges: list[str] | tuple[str, ...] | None = None, column_widths: dict | None = None, autofit_rows: int | None = 1000, autofit_padding: float = 0.0, hidden_columns: list | tuple | set | None = None, row_heights: dict | None = None, hidden_rows: list | tuple | set | None = None, row_groups: list | tuple | None = None, column_groups: list | tuple | None = None, freeze_panes: str | None = None, auto_filter: bool | None = None, auto_filter_ref: str | None = None, charts: list | tuple | None = None, images: list | tuple | None = None, print_settings: PrintSettings | None = None, data_validations: list | tuple | None = None, tables: list | tuple | None = None, conditional_formats: list | tuple | None = None, comments: Mapping[str, Comment] | None = None, sheet_protection: SheetProtection | None = None, show_grid_lines: bool = True, tab_color: Color | str | None = None, zoom: int | None = None, show_row_col_headers: bool = True, show_zero_values: bool = True, right_to_left: bool = False, pivots: list | tuple | None = None) -> None
```

Write a pandas or polars DataFrame to the current sheet.

pandas and polars are optional: they are imported lazily only when a DataFrame is actually passed in.

##### Parameters

df: A `pandas.DataFrame` or `polars.DataFrame`. include\_index: pandas only -- prepend the index as leading column(s). na\_rep: Value for missing cells, defaults to `None` (empty cell). formats: Optional `{column_name: format_string}` mapping (see `xlspy.F`).

## SheetOptions

```
SheetOptions(header_style: Style | None = None, styles: dict[str, Style] | None = None, merges: list[str] | tuple[str, ...] | None = None, conditional_formats: list | tuple | None = None, tables: list | tuple | None = None, column_widths: dict | None = None, autofit_rows: int = 1000, autofit_padding: float = 0.0, hidden_columns: list | tuple | set | None = None, row_heights: dict | None = None, hidden_rows: list | tuple | set | None = None, row_groups: list | tuple | None = None, column_groups: list | tuple | None = None, freeze_panes: str | None = None, auto_filter: bool | None = None, auto_filter_ref: str | None = None, charts: list | tuple | None = None, data_validations: list | tuple | None = None, images: list | tuple | None = None, print_settings: PrintSettings | None = None, comments: Mapping[str, Any] | None = None, threaded_comments: Mapping[str, Any] | None = None, sheet_protection: SheetProtection | None = None, show_grid_lines: bool = True, header_rows: int = 1, tab_color: Color | str | None = None, zoom: int | None = None, ignored_errors: list | tuple | None = None, sparklines: list | tuple | None = None, slicers: list | tuple | None = None, pivots: list | tuple | None = None, shapes: list | tuple | None = None, show_row_col_headers: bool = True, show_zero_values: bool = True, right_to_left: bool = False, sort_state: Any | None = None)
```

Every option of `write_sheet` except the rows. Defaults match the call defaults.

## F

Format string constants for cell number formatting.

Use with writers by passing (value, format\_string) tuples: writer.write\_sheet(\[ \["Name", "Value"\], \["Revenue", (100000, F.THOUSANDS\_SEP)\], \["Date", (date(2026, 6, 1), F.DATE\_SHORT)\], \])

## to\_xlsx

```
to_xlsx(df: Any, path: _Target, sheet_name: str = 'Sheet1', *, include_index: bool = False, na_rep: Any = None, formats: dict[str, str] | None = None, header_style: Style | None = None, styles: dict | None = None, merges: list[str] | tuple[str, ...] | None = None, conditional_formats: list | tuple | None = None, tables: Any = None, column_widths: dict | None = None, autofit_rows: int | None = 1000, autofit_padding: float = 0.0, hidden_columns: Any = None, row_heights: dict | None = None, hidden_rows: Any = None, row_groups: Any = None, column_groups: Any = None, freeze_panes: str | None = None, auto_filter: bool | None = None, charts: Any = None, comments: Any = None, threaded_comments: Any = None, sheet_protection: SheetProtection | None = None, **writer_kwargs: Any) -> _Target
```

Write a DataFrame straight to an `.xlsx` file and return `path`.

A failed conversion leaves `path` as it was: the writer stages the file and publishes it only on success.

Examples:

```
import pandas as pd

from xlspy import to_xlsx

df = pd.DataFrame({"name": ["Alice", "Bob"], "age": [25, 30]})
to_xlsx(df, "people.xlsx")
```

All sheet options of `write_dataframe` are accepted as keywords:

```
to_xlsx(df, "people.xlsx", freeze_panes="A2", include_index=True)
```

**See Also**

`to_xlsb` for the binary format, and `XlsxWriter.write_dataframe` for writing into a workbook that already has sheets and objects.

## to\_xlsb

```
to_xlsb(df: Any, path: _Target, sheet_name: str = 'Sheet1', *, include_index: bool = False, na_rep: Any = None, formats: dict[str, str] | None = None, header_style: Style | None = None, styles: dict | None = None, merges: list[str] | tuple[str, ...] | None = None, column_widths: dict | None = None, autofit_rows: int | None = 1000, autofit_padding: float = 0.0, hidden_columns: Any = None, row_heights: dict | None = None, hidden_rows: Any = None, row_groups: Any = None, column_groups: Any = None, freeze_panes: str | None = None, auto_filter: bool | None = None, charts: Any = None, tables: Any = None, conditional_formats: Any = None, comments: Any = None, sheet_protection: SheetProtection | None = None, **writer_kwargs: Any) -> _Target
```

Write a DataFrame straight to an `.xlsb` file and return `path`.

A failed conversion leaves `path` as it was: the writer stages the file and publishes it only on success.

Examples:

```
import polars as pl

from xlspy import to_xlsb

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

The result is a binary XLSB workbook with a single `Sheet1`. Use `XlsbWriter.write_dataframe` to add more sheets, styles or charts.

**See Also**

`to_xlsx` for maximum compatibility, and `XlsbWriter` for the full writer API.

## dataframe\_to\_rows

```
dataframe_to_rows(df: Any, include_index: bool = False, na_rep: Any = None, formats: dict[str, str] | None = None) -> Iterator[list[Any]]
```

Yield a pandas or polars DataFrame as rows ready for `write_sheet`.

#### Parameters

df: A `pandas.DataFrame` or `polars.DataFrame`. include\_index: pandas only -- prepend the index (all levels of a MultiIndex) as leading columns. polars has no index and raises `ValueError`. na\_rep: Value written for missing cells (`None`/`NaN`/`NaT`/`NA`). Defaults to `None`, i.e. an empty cell. formats: Optional mapping of column name to a format string (see `xlspy.F`), e.g. `{"date": F.DATE_ISO, "price": F.CURRENCY_PLN}`.

The result is a generator, so the XLSB writer keeps streaming row by row.
