Skip to content

Writing

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

API reference · Guide

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.

Source code in src/xlspy/xlsx_writer.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
def __init__(
    self,
    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,
) -> None:
    reject_unknown_arguments(type(self).__name__, unknown)
    self._coercion = check_options(strings_to_formulas, strings_to_numbers, strings_to_urls, nan_inf_to_errors)
    self._file = file
    self._worksheet_data: list[tuple[str, Iterable[list[Any]] | None, bool]] = []
    self._shared_strings: list[str | tuple[str, str]] = []
    self._shared_strings_dict: dict[str | tuple[str, str], int] = {}
    self._sheet_count = 0
    self._sst_unique_count = 0
    self._sst_all_count = 0
    self._filtered_data_list: list[FilterData] = []
    self._sheet_number = 1
    self._compression_level = compression_level
    self._use_shared_strings = use_shared_strings
    self._spool_max_bytes = spool_max_bytes
    self._zf: PackageZip = None  # type: ignore[assignment]  # set when the workbook opens
    self._output = None  # StagedOutput while open
    self._letters = self._generate_column_letters()
    self._aborted = False
    self._saved = False
    # Set when a dynamic-array formula is written: xl/metadata.xml follows.
    self._has_dynamic = False

    # The default date and date-time formats, the same as XlsbWriter's.
    # Excel's built-in formats 14 and 22 would follow the reader's locale.
    self._format_registry: dict[str, int] = {DEFAULT_DATE_FORMAT: 164, DEFAULT_DATETIME_FORMAT: 165}
    self._format_xf_map: dict[str, int] = {}
    self._style_xf_map: dict[Style, int] = {}
    self._xf_styles: dict[int, Style] = {}
    self._style_format_xf: dict[tuple, tuple] = {}
    # xf of each (value, format) cell the native row encoder may reuse: keyed
    # by the format, or by (cell style xf, format) for a styled cell.
    self._fmt_xf: dict = {}
    self._fmt_xf_styles: list = []
    # Font id 0 is “no font”, id 1 is the builtin bold default emitted by
    # _create_styles_xml; custom fonts start at 2.
    self._font_registry: dict[tuple, int] = {}
    self._fill_registry: dict[tuple, int] = {}
    self._border_registry: dict[tuple, int] = {}
    self._style_components: dict[int, tuple] = {}
    self._dxf_list: list[tuple] = []
    self._dxf_index: dict[tuple, int] = {}
    self._dxf_font_registry: dict[tuple, int] = {}
    self._dxf_fill_registry: dict[tuple, int] = {}
    self._dxf_border_registry: dict[tuple, int] = {}
    self._seen_cf_priorities: set[int] = set()
    self._reserved_cf_priorities: set[int] = set()
    self._next_cf_priority = 1
    self._next_table_id = 1
    self._table_names: set[str] = set()
    self._tables_xml: dict[int, str] = {}
    # Casefolded table name -> (table id, column names), for slicer caches.
    self._table_info: dict[str, tuple[int, list[str]]] = {}
    # Slicer names, cache names and (table, column) targets used workbook-wide.
    self._slicer_names: set[str] = set()
    self._slicer_caches: set[str] = set()
    self._slicer_targets: set[tuple[str, str]] = set()
    # Each slicer owns one slicer part and one cache, both numbered alike.
    self._next_slicer_part = 1
    self._sheet_slicers: dict[int, list[Slicer]] = {}
    self._sheet_shapes: dict[int, list[Shape]] = {}
    # Pivot-table names, rendered pivots and cells waiting for their target sheet.
    self._pivot_names: set[str] = set()
    self._next_pivot_id = 1
    self._pivot_renders: list = []
    self._pending_pivots: dict[str, list] = {}
    # (path, xml, content type) of each slicer and cache part, in write order.
    self._slicer_part_files: list[tuple[str, str, str]] = []
    # Cache defined names; cache i is the workbook relationship of index i.
    self._slicer_cache_names: list[str] = []
    self._sheet_charts: dict[int, list] = {}
    self._sheet_chart_ids: dict[int, list[int]] = {}
    self._sheet_drawings: set[int] = set()
    self._sheet_images: dict[int, list[Image]] = {}
    self._sheet_image_media: dict[int, list[str]] = {}
    self._media = MediaParts()
    self._sheet_written: set[int] = set()
    self._sheet_rels: dict[int, list[tuple[str, str, str, bool]]] = {}
    self._sheet_print: dict[int, PrintSettings] = {}
    self._internal_links: list[tuple[int, str]] = []
    self._charts_xml: dict[int, tuple[int, int, str]] = {}
    self._next_chart_id = 1
    self._next_numfmt_id = 166
    self._next_xf_index = 4
    self._sheet_comments: dict[int, dict[str, Comment]] = {}
    self._sheet_threaded_comments: dict[int, dict[str, ThreadedComment]] = {}
    self._defined_names: dict[tuple[str, str | None], DefinedName] = {}
    self._workbook_protection: WorkbookProtection | None = None
    self._vba_project: bytes | None = None
    self._vba_name: str | None = None

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.

Source code in src/xlspy/xlsx_writer.py
323
324
325
326
327
328
329
330
331
def add_vba_project(self, project: str | os.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.
    """
    self._require_writable()
    self._vba_project = read_vba_project(project)

set_vba_name

set_vba_name(name: str) -> None

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

Source code in src/xlspy/xlsx_writer.py
333
334
335
336
def set_vba_name(self, name: str) -> None:
    """Set the workbook code name (``workbookPr/@codeName``) for the VBA project."""
    self._require_writable()
    self._vba_name = check_vba_name(name)

set_defined_name

set_defined_name(definition: DefinedName) -> None

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

Source code in src/xlspy/xlsx_writer.py
338
339
340
341
342
343
def set_defined_name(self, definition: DefinedName) -> None:
    """Set a global or worksheet-local name; local titles are checked on save."""
    self._require_writable()
    if not isinstance(definition, DefinedName):
        raise TypeError("definition must be a DefinedName")
    self._defined_names[(definition.name.casefold(), definition.scope)] = definition

get_defined_names

get_defined_names() -> list[DefinedName]

The defined names set so far.

Source code in src/xlspy/xlsx_writer.py
345
346
347
def get_defined_names(self) -> list[DefinedName]:
    """The defined names set so far."""
    return list(self._defined_names.values())

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.

Source code in src/xlspy/xlsx_writer.py
349
350
351
352
353
def remove_defined_name(self, name: str, scope: str | None = None) -> None:
    """Remove a defined name; with ``scope``, the one local to that sheet."""
    self._require_writable()
    DefinedName(name, "0", scope)
    self._defined_names.pop((name.casefold(), scope), None)

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.

Source code in src/xlspy/doc_properties.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def set_properties(
    self,
    *,
    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.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.
    """
    self._require_writable()
    values = {
        "title": title,
        "subject": subject,
        "author": author,
        "manager": manager,
        "company": company,
        "category": category,
        "keywords": keywords,
        "comments": comments,
        "status": status,
    }
    props: dict[str, Any] = {key: _check_doc_text(key, value) for key, value in values.items() if value is not None}
    if created is None:
        created = _datetime.datetime.now(_datetime.UTC)
    props["created"] = _utc(created, "created")
    custom_xml = []
    if custom is not None:
        if not isinstance(custom, dict):
            raise TypeError("custom must be a dict of property names to values")
        seen = set()
        for name, value in custom.items():
            _check_doc_text("custom property name", name)
            if not name.strip() or len(name) > _MAX_CUSTOM_NAME:
                raise ValueError(f"custom property names must be 1-{_MAX_CUSTOM_NAME} characters")
            if name.casefold() in seen:
                raise ValueError(f"duplicate custom property {name!r} (names ignore case)")
            seen.add(name.casefold())
            custom_xml.append((name, _custom_value(name, value)))
    props["custom"] = custom_xml
    self._doc_props = props

set_workbook_protection

set_workbook_protection(protection: WorkbookProtection) -> None

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

Source code in src/xlspy/_output.py
195
196
197
198
199
200
def set_workbook_protection(self, protection: WorkbookProtection) -> None:
    """Lock the workbook structure, with a password when one is given."""
    self._require_writable()
    if not isinstance(protection, WorkbookProtection):
        raise TypeError("protection must be WorkbookProtection")
    self._workbook_protection = protection

save

save() -> None

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

Source code in src/xlspy/_output.py
238
239
240
241
242
243
244
245
246
def save(self) -> None:
    """Write the workbook parts. The file is published when the writer closes."""
    self._require_writable()
    try:
        self._write_workbook_parts()
    except BaseException:
        self._aborted = True
        raise
    self._saved = True

close

close() -> None

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

Source code in src/xlspy/_output.py
248
249
250
def close(self) -> None:
    """Close the writer, publishing the workbook if ``save()`` succeeded."""
    self._finish(publish=True)

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.

Source code in src/xlspy/_xlsx_writer_sheet.py
107
108
109
110
111
112
113
114
115
116
117
118
def write_sheet(self, 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.
    """
    opts = resolve_sheet_options(options, kwargs, XLSX_OPTIONS, "XlsxWriter")
    self._write_sheet(data, opts)

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).

Source code in src/xlspy/_xlsx_writer_sheet.py
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
def write_dataframe(
    self,
    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``).
    """

    self.write_sheet(
        dataframe_to_rows(df, include_index=include_index, na_rep=na_rep, formats=formats),
        header_style=header_style,
        styles=styles,
        merges=merges,
        conditional_formats=conditional_formats,
        tables=tables,
        column_widths=column_widths,
        autofit_rows=autofit_rows,
        autofit_padding=autofit_padding,
        hidden_columns=hidden_columns,
        row_heights=row_heights,
        hidden_rows=hidden_rows,
        row_groups=row_groups,
        column_groups=column_groups,
        freeze_panes=freeze_panes,
        auto_filter=auto_filter,
        charts=charts,
        data_validations=data_validations,
        images=images,
        print_settings=print_settings,
        comments=comments,
        threaded_comments=threaded_comments,
        sheet_protection=sheet_protection,
        show_grid_lines=show_grid_lines,
        tab_color=tab_color,
        zoom=zoom,
        show_row_col_headers=show_row_col_headers,
        show_zero_values=show_zero_values,
        right_to_left=right_to_left,
        pivots=pivots,
    )

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.

Source code in src/xlspy/writer.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def __init__(
    self,
    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,
) -> None:
    reject_unknown_arguments(type(self).__name__, unknown)
    self._coercion = check_options(strings_to_formulas, strings_to_numbers, strings_to_urls, nan_inf_to_errors)
    self._file = file
    self._use_shared_strings = use_shared_strings
    self._aborted = False
    self._saved = False
    self._output = None  # StagedOutput while open
    self._worksheet_data: list[tuple[str, Iterable[list[Any]], bool]] = []
    # A rich-text entry is ("rich", text, runs) and only the Python SST writer encodes it.
    self._shared_strings: list[str | tuple[str, str, tuple[Any, ...]]] = []
    self._shared_strings_dict: dict[str | tuple[str, str, tuple[Any, ...]], int] = {}
    self._sheet_count = 0
    self._sst_unique_count = 0
    self._sst_all_count = 0
    # Rich entries are tuples, which only the Python SST writer encodes.
    self._sst_has_rich = False
    self._filtered_data_list: list[FilterData] = []
    self._sheet_number = 1
    self._compression_level = compression_level
    # The package being written; set by open() and typed loosely because the
    # threaded ZipFile in _zip_threads adds methods that zipfile.ZipFile lacks.
    self._zf: Any = None
    self._letters = chart_parts.column_letters()

    self._format_registry: dict[str, int] = {}
    self._format_xf_map: dict[str, int] = {}
    self._style_xf_map: dict[Style, int] = {}
    self._xf_styles: dict[int, Style] = {}
    self._style_format_xf: dict[tuple, tuple] = {}
    # xf of each (value, format) cell the native row encoder may reuse: keyed
    # by the format, or by (cell style xf, format) for a styled cell.
    self._fmt_xf: dict = {}
    self._fmt_xf_styles: list = []
    self._style_components: dict[int, tuple] = {}
    self._font_registry: dict[tuple, int] = {}
    self._fill_registry: dict[tuple, int] = {}
    self._border_registry: dict[tuple, int] = {}
    self._next_numfmt_id = 167
    self._next_xf_index = 4
    self._sheet_charts: dict[int, list] = {}
    self._sheet_chart_ids: dict[int, list[int]] = {}
    self._sheet_chart_cells: dict[int, dict] = {}
    self._next_chart_id = 1
    # Sheets with a drawing part: charts, pictures or both.
    self._sheet_drawings: set[int] = set()
    self._sheet_images: dict[int, list[Image]] = {}
    self._sheet_shapes: dict[int, list[Shape]] = {}
    self._sheet_image_media: dict[int, list[str]] = {}
    self._media = MediaParts()
    # Sheet index -> print settings; print area and titles become names.
    self._sheet_print: dict[int, PrintSettings] = {}
    # BrtDXF payload -> index, for conditional formats with a style.
    self._dxf_index: dict[bytes, int] = {}
    self._next_table_id = 1
    self._table_registry: dict[int, tuple[str, list[str], str]] = {}
    self._sheet_table_scope: tuple | None = None
    self._table_names: set[str] = set()
    self._sheet_tables: dict[int, list[tuple]] = {}
    self._tables_bin: dict[int, bytes] = {}
    # Casefolded slicer names, cache names and (table, column) pairs already used.
    self._slicer_names: set[str] = set()
    self._slicer_caches: set[str] = set()
    self._slicer_targets: set[tuple[str, str]] = set()
    self._sheet_slicers: dict[int, list[Slicer]] = {}
    # Sheet id -> (slicer part number, relationship id); one part holds a sheet's slicers.
    self._sheet_slicer_parts: dict[int, tuple[int, str]] = {}
    # Cache names, in cache part order (slicerCache1.bin, ...).
    self._slicer_cache_names: list[str] = []
    # Casefolded pivot-table names, the rendered pivots (cache i is workbook
    # relationship i), the sheet each is placed on and cells waiting for a
    # target sheet that is written later.
    self._pivot_names: set[str] = set()
    self._pivot_renders: list = []
    self._sheet_pivots: dict[int, list] = {}
    self._pending_pivots: dict[str, list] = {}
    self._written_sheets: set[int] = set()
    # Set when a dynamic-array formula is written: xl/metadata.bin follows.
    self._has_dynamic = False
    self._seen_cf_priorities: set[int] = set()
    self._reserved_cf_priorities: set[int] = set()
    self._next_cf_priority = 1
    self._xlsb_formula_context = None
    self._sheet_comments: dict[int, Any] = {}
    self._sheet_link_rels: dict[int, Any] = {}
    self._workbook_protection = None

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.

Source code in src/xlspy/doc_properties.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def set_properties(
    self,
    *,
    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.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.
    """
    self._require_writable()
    values = {
        "title": title,
        "subject": subject,
        "author": author,
        "manager": manager,
        "company": company,
        "category": category,
        "keywords": keywords,
        "comments": comments,
        "status": status,
    }
    props: dict[str, Any] = {key: _check_doc_text(key, value) for key, value in values.items() if value is not None}
    if created is None:
        created = _datetime.datetime.now(_datetime.UTC)
    props["created"] = _utc(created, "created")
    custom_xml = []
    if custom is not None:
        if not isinstance(custom, dict):
            raise TypeError("custom must be a dict of property names to values")
        seen = set()
        for name, value in custom.items():
            _check_doc_text("custom property name", name)
            if not name.strip() or len(name) > _MAX_CUSTOM_NAME:
                raise ValueError(f"custom property names must be 1-{_MAX_CUSTOM_NAME} characters")
            if name.casefold() in seen:
                raise ValueError(f"duplicate custom property {name!r} (names ignore case)")
            seen.add(name.casefold())
            custom_xml.append((name, _custom_value(name, value)))
    props["custom"] = custom_xml
    self._doc_props = props

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.

Source code in src/xlspy/_writer_common.py
154
155
156
157
158
159
160
161
def add_sheet(self, sheet_name: str, hidden: bool = False) -> None:
    """Start a new sheet; the next ``write_sheet`` call fills it.

    ``hidden=True`` hides the sheet.
    """
    check_sheet_name(sheet_name, (name for name, _data, _hidden in self._worksheet_data))
    self._sheet_count += 1
    self._worksheet_data.append((sheet_name, iter([]), hidden))

set_defined_name

set_defined_name(definition: DefinedName) -> None

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

Source code in src/xlspy/_xlsb_writer.py
40
41
42
43
def set_defined_name(self, definition: DefinedName) -> None:
    """Add a defined name, replacing one with the same name and scope."""
    self._require_writable()
    self._formula_context().set_name(definition)

get_defined_names

get_defined_names() -> list[DefinedName]

The defined names set so far.

Source code in src/xlspy/_xlsb_writer.py
45
46
47
def get_defined_names(self) -> list[DefinedName]:
    """The defined names set so far."""
    return self._xlsb_formula_context.defined_names() if self._xlsb_formula_context is not None else []

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.

Source code in src/xlspy/_xlsb_writer.py
49
50
51
52
53
54
def remove_defined_name(self, name: str, scope: str | None = None) -> None:
    """Remove a defined name; with ``scope``, the one local to that sheet."""
    self._require_writable()
    DefinedName(name, "0", scope)
    if self._xlsb_formula_context is not None:
        self._xlsb_formula_context.remove_name(name, scope)

set_workbook_protection

set_workbook_protection(protection: WorkbookProtection) -> None

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

Source code in src/xlspy/_output.py
195
196
197
198
199
200
def set_workbook_protection(self, protection: WorkbookProtection) -> None:
    """Lock the workbook structure, with a password when one is given."""
    self._require_writable()
    if not isinstance(protection, WorkbookProtection):
        raise TypeError("protection must be WorkbookProtection")
    self._workbook_protection = protection

save

save() -> None

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

Source code in src/xlspy/_output.py
238
239
240
241
242
243
244
245
246
def save(self) -> None:
    """Write the workbook parts. The file is published when the writer closes."""
    self._require_writable()
    try:
        self._write_workbook_parts()
    except BaseException:
        self._aborted = True
        raise
    self._saved = True

close

close() -> None

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

Source code in src/xlspy/_output.py
248
249
250
def close(self) -> None:
    """Close the writer, publishing the workbook if ``save()`` succeeded."""
    self._finish(publish=True)

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.

Source code in src/xlspy/_xlsb_writer_sheet.py
40
41
42
43
44
45
46
47
48
def write_sheet(self, 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``.
    """
    opts = resolve_sheet_options(options, kwargs, XLSB_OPTIONS, "XlsbWriter")
    self._write_sheet(data, opts)

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).

Source code in src/xlspy/_xlsb_writer_sheet.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
def write_dataframe(
    self,
    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``).
    """

    self.write_sheet(
        dataframe_to_rows(df, include_index=include_index, na_rep=na_rep, formats=formats),
        header_style=header_style,
        styles=styles,
        merges=merges,
        column_widths=column_widths,
        autofit_rows=autofit_rows,
        autofit_padding=autofit_padding,
        hidden_columns=hidden_columns,
        row_heights=row_heights,
        hidden_rows=hidden_rows,
        row_groups=row_groups,
        column_groups=column_groups,
        freeze_panes=freeze_panes,
        auto_filter=auto_filter,
        auto_filter_ref=auto_filter_ref,
        charts=charts,
        images=images,
        print_settings=print_settings,
        data_validations=data_validations,
        tables=tables,
        conditional_formats=conditional_formats,
        comments=comments,
        sheet_protection=sheet_protection,
        show_grid_lines=show_grid_lines,
        tab_color=tab_color,
        zoom=zoom,
        show_row_col_headers=show_row_col_headers,
        show_zero_values=show_zero_values,
        right_to_left=right_to_left,
        pivots=pivots,
    )

SheetOptions dataclass

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.

Source code in src/xlspy/dataframe.py
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def 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:
        ```python
        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:

        ```python
        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.
    """
    with XlsxWriter(path, **writer_kwargs) as writer:
        writer.add_sheet(sheet_name)
        writer.write_dataframe(
            df,
            include_index=include_index,
            na_rep=na_rep,
            formats=formats,
            header_style=header_style,
            styles=styles,
            merges=merges,
            conditional_formats=conditional_formats,
            tables=tables,
            column_widths=column_widths,
            autofit_rows=autofit_rows,
            autofit_padding=autofit_padding,
            hidden_columns=hidden_columns,
            row_heights=row_heights,
            hidden_rows=hidden_rows,
            row_groups=row_groups,
            column_groups=column_groups,
            freeze_panes=freeze_panes,
            auto_filter=auto_filter,
            charts=charts,
            comments=comments,
            threaded_comments=threaded_comments,
            sheet_protection=sheet_protection,
        )
    return path

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.

Source code in src/xlspy/dataframe.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def 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:
        ```python
        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.
    """
    with XlsbWriter(path, **writer_kwargs) as writer:
        writer.add_sheet(sheet_name)
        writer.write_dataframe(
            df,
            include_index=include_index,
            na_rep=na_rep,
            formats=formats,
            header_style=header_style,
            styles=styles,
            merges=merges,
            column_widths=column_widths,
            autofit_rows=autofit_rows,
            autofit_padding=autofit_padding,
            hidden_columns=hidden_columns,
            row_heights=row_heights,
            hidden_rows=hidden_rows,
            row_groups=row_groups,
            column_groups=column_groups,
            freeze_panes=freeze_panes,
            auto_filter=auto_filter,
            charts=charts,
            tables=tables,
            conditional_formats=conditional_formats,
            comments=comments,
            sheet_protection=sheet_protection,
        )
    return path

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.

Source code in src/xlspy/_dataframe_rows.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
def 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.
    """
    if _is_pandas_frame(df):
        headers, rows = _pandas_rows(df, include_index)
    elif _is_polars_frame(df):
        headers, rows = _polars_rows(df, include_index)
    else:
        raise TypeError(
            "Expected a pandas or polars DataFrame, got "
            f"{type(df).__module__}.{type(df).__qualname__}. "
            "Install pandas or polars to use write_dataframe()."
        )

    # Optional modules resolved once per conversion instead of once per cell.
    pd = _get_pandas()
    np = _get_numpy()

    format_for = _format_lookup(headers, formats)

    yield headers
    native = _accel.convert_frame_row
    if native is not None:
        # The plain values are decided in Rust; any other cell comes back here.
        missing = () if pd is None else (pd.NA, pd.NaT)
        timestamp = None if pd is None else pd.Timestamp

        def slow(cell: Any, fmt: str | None) -> Any:
            return _convert_cell(cell, fmt, na_rep, pd, np)

        for row in rows:
            converted = native(row, format_for, na_rep, missing, timestamp, slow)
            yield (
                converted
                if converted is not None
                else [_convert_cell(cell, fmt, na_rep, pd, np) for cell, fmt in zip(row, format_for)]
            )
        return
    for row in rows:
        yield [_convert_cell(cell, fmt, na_rep, pd, np) for cell, fmt in zip(row, format_for)]