Skip to content

API reference

The importable Python surface: write_xlsx, the package's one public function, which the core discovers through the bankstatementparser.writers entry point. Generated from the docstrings by mkdocstrings.

bankstatementparser_writer_xlsx.writer

Excel .xlsx writer for parsed bank-statement data.

This module turns the output of a bankstatementparser parser into a polished Excel workbook via openpyxl.

The single public entry point is :func:write_xlsx, which accepts any of three input shapes and normalises them to a flat, rectangular table:

  • a :class:pandas.DataFrame (as returned by a parser's .parse()),
  • a list of :class:bankstatementparser.Transaction objects, or
  • a list of plain dict row records.

The resulting workbook has a bold header row followed by one row per record on the Transactions sheet, with column widths auto-sized for readability. An optional summary mapping (e.g. the output of a parser's get_summary()) is written to a second Summary sheet as key/value rows.

Value coercion

Cells must hold spreadsheet-friendly values, so the writer coerces the rich Python types the parser emits:

  • :class:decimal.Decimal is written as a float (Excel has no decimal type; floats sort and aggregate natively in spreadsheets).
  • :class:datetime.date and :class:datetime.datetime are written unchanged — openpyxl serialises them as native Excel date cells.
  • Every other value is written as-is when openpyxl accepts it (str, int, float, bool, None) and otherwise stringified via str().

write_xlsx(data, path, *, sheet_name='Transactions', summary=None)

Write parsed bank-statement data to a .xlsx workbook.

Parameters:

Name Type Description Default
data Any

The records to serialise. One of:

  • a :class:pandas.DataFrame (as returned by a bankstatementparser parser's .parse() method) — its columns define the header order;
  • a list of :class:bankstatementparser.Transaction objects — serialised with a stable column order;
  • a list of plain dict records — the header is the union of keys in first-seen order.

An empty list (or empty DataFrame) is accepted and writes a header-only sheet (header omitted entirely when no columns can be determined).

required
path str | Path

The output .xlsx file path. The parent directory must already exist; an existing file is overwritten.

required
sheet_name str

The title of the sheet holding the transaction rows. Defaults to "Transactions".

'Transactions'
summary Mapping[str, Any] | None

Optional mapping (e.g. a parser's get_summary() result) written to a second "Summary" sheet as one key/value row per item, under a bold Key/Value header.

None

Returns:

Name Type Description
The Path

class:~pathlib.Path of the written workbook.

Raises:

Type Description
TypeError

If data is neither a DataFrame, nor a list/tuple of Transaction objects, nor a list/tuple of dict records (and is not empty).

ValueError

If data is a non-empty sequence whose items mix dict and non-dict types, or contain an unsupported item type; or if a value, a column name or the summary holds a control character an .xlsx cannot store (C0 characters other than tab, newline and carriage return).

Source code in bankstatementparser_writer_xlsx/writer.py
 93
 94
 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
149
150
151
152
def write_xlsx(
    data: Any,
    path: str | Path,
    *,
    sheet_name: str = "Transactions",
    summary: Mapping[str, Any] | None = None,
) -> Path:
    """Write parsed bank-statement ``data`` to a ``.xlsx`` workbook.

    Args:
        data: The records to serialise. One of:

            * a :class:`pandas.DataFrame` (as returned by a
              ``bankstatementparser`` parser's ``.parse()`` method) —
              its columns define the header order;
            * a list of :class:`bankstatementparser.Transaction`
              objects — serialised with a stable column order;
            * a list of plain ``dict`` records — the header is the
              union of keys in first-seen order.

            An empty list (or empty DataFrame) is accepted and writes a
            header-only sheet (header omitted entirely when no columns
            can be determined).
        path: The output ``.xlsx`` file path. The parent directory must
            already exist; an existing file is overwritten.
        sheet_name: The title of the sheet holding the transaction rows.
            Defaults to ``"Transactions"``.
        summary: Optional mapping (e.g. a parser's ``get_summary()``
            result) written to a second ``"Summary"`` sheet as one
            ``key``/``value`` row per item, under a bold ``Key``/``Value``
            header.

    Returns:
        The :class:`~pathlib.Path` of the written workbook.

    Raises:
        TypeError: If ``data`` is neither a DataFrame, nor a list/tuple
            of ``Transaction`` objects, nor a list/tuple of ``dict``
            records (and is not empty).
        ValueError: If ``data`` is a non-empty sequence whose items mix
            ``dict`` and non-``dict`` types, or contain an unsupported
            item type; or if a value, a column name or the summary
            holds a control character an ``.xlsx`` cannot store (C0
            characters other than tab, newline and carriage return).
    """
    columns, rows = _normalise(data)

    workbook = Workbook()
    sheet = workbook.active
    sheet.title = sheet_name
    try:
        _write_table(sheet, columns, rows)
        if summary is not None:
            _write_summary(workbook.create_sheet("Summary"), summary)
    except IllegalCharacterError as exc:  # XML 1.0 cannot hold the text
        raise ValueError(str(exc)) from exc

    output = Path(path)
    workbook.save(output)
    return output