pola-rs/polars · error · RuntimeError

sparkline data range/cols must all be adjacent

Error message

sparkline data range/cols must all be adjacent

What it means

write_excel raises this when the sparkline 'columns' (or the columns embedded in a sparkline format string) do not form one contiguous block of columns in the DataFrame. xlsx sparklines require a single continuous data range, so non-adjacent columns cannot be expressed.

Solutions

  1. Reorder the DataFrame so the sparkline source columns are contiguous before calling write_excel (e.g. df.select([...adjacent...])).
  2. Select a contiguous range of columns for the sparkline, or split into multiple sparklines each over adjacent columns.
  3. Check with a quick assertion that the chosen columns are adjacent in df.columns before writing.

Example fix

// before
df.write_excel('out.xlsx', sparklines={'line': {'columns': ['q1', 'q3']}})
// after
df = df.select(['q1', 'q2', 'q3'])  # ensure adjacency
df.write_excel('out.xlsx', sparklines={'line': {'columns': ['q1', 'q2', 'q3']}})
Defensive patterns

Strategy: validation

Validate before calling

names = spark_cols
idx = [df.columns.index(c) for c in names]
assert all(idx[i+1] - idx[i] == 1 for i in range(len(idx)-1)), 'sparkline columns must be adjacent'

Prevention

When it happens

Trigger: Calling df.write_excel(sparklines={'line': '...'} ) or passing a 'columns' param whose selected columns are separated by other columns (e.g. ['a','c'] where 'b' sits between them), so _adjacent_cols fails.

Common situations: Users select sparkline source columns by name after adding/reordering columns, leaving gaps; or reference columns that were reordered between writer versions.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/c644b1653fdaf75c. Report an issue: GitHub.

Appendix: source

Thrown at py-polars/src/polars/io/spreadsheet/_write_utils.py:305

    ws: Worksheet,
    df: DataFrame,
    table_start: tuple[int, int],
    col: str,
    *,
    include_header: bool,
    params: Sequence[str] | dict[str, Any],
) -> None:
    """Inject sparklines into (previously-created) empty table columns."""
    from xlsxwriter.utility import xl_rowcol_to_cell

    m: dict[str, Any] = {}
    data_cols = params.get("columns") if isinstance(params, dict) else params
    if not data_cols:
        msg = "supplying 'columns' param value is mandatory for sparklines"
        raise ValueError(msg)
    elif not _adjacent_cols(df, data_cols, min_max=m):
        msg = "sparkline data range/cols must all be adjacent"
        raise RuntimeError(msg)

    spk_row, spk_col, _, _ = _xl_column_range(
        df, table_start, col, include_header=include_header, as_range=False
    )
    data_start_col = table_start[1] + m["min"]["idx"]
    data_end_col = table_start[1] + m["max"]["idx"]

    if not isinstance(params, dict):
        options = {}
    else:
        # strip polars-specific params before passing to xlsxwriter
        options = {
            name: val
            for name, val in params.items()
            if name not in ("columns", "insert_after", "insert_before")
        }
        if "negative_points" not in options:
            options["negative_points"] = options.get("type") in ("column", "win_loss")

View on GitHub (pinned to fe841f959e)