{"record":{"id":"c644b1653fdaf75c","repo":"pola-rs/polars","slug":"sparkline-data-range-cols-must-all-be-adjacent","errorCode":null,"errorMessage":"sparkline data range/cols must all be adjacent","messagePattern":"sparkline data range/cols must all be adjacent","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/io/spreadsheet/_write_utils.py","lineNumber":305,"sourceCode":"    ws: Worksheet,\n    df: DataFrame,\n    table_start: tuple[int, int],\n    col: str,\n    *,\n    include_header: bool,\n    params: Sequence[str] | dict[str, Any],\n) -> None:\n    \"\"\"Inject sparklines into (previously-created) empty table columns.\"\"\"\n    from xlsxwriter.utility import xl_rowcol_to_cell\n\n    m: dict[str, Any] = {}\n    data_cols = params.get(\"columns\") if isinstance(params, dict) else params\n    if not data_cols:\n        msg = \"supplying 'columns' param value is mandatory for sparklines\"\n        raise ValueError(msg)\n    elif not _adjacent_cols(df, data_cols, min_max=m):\n        msg = \"sparkline data range/cols must all be adjacent\"\n        raise RuntimeError(msg)\n\n    spk_row, spk_col, _, _ = _xl_column_range(\n        df, table_start, col, include_header=include_header, as_range=False\n    )\n    data_start_col = table_start[1] + m[\"min\"][\"idx\"]\n    data_end_col = table_start[1] + m[\"max\"][\"idx\"]\n\n    if not isinstance(params, dict):\n        options = {}\n    else:\n        # strip polars-specific params before passing to xlsxwriter\n        options = {\n            name: val\n            for name, val in params.items()\n            if name not in (\"columns\", \"insert_after\", \"insert_before\")\n        }\n        if \"negative_points\" not in options:\n            options[\"negative_points\"] = options.get(\"type\") in (\"column\", \"win_loss\")","sourceCodeStart":287,"sourceCodeEnd":323,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/io/spreadsheet/_write_utils.py#L287-L323","documentation":"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.","triggerScenarios":"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.","commonSituations":"Users select sparkline source columns by name after adding/reordering columns, leaving gaps; or reference columns that were reordered between writer versions.","solutions":["Reorder the DataFrame so the sparkline source columns are contiguous before calling write_excel (e.g. df.select([...adjacent...])).","Select a contiguous range of columns for the sparkline, or split into multiple sparklines each over adjacent columns.","Check with a quick assertion that the chosen columns are adjacent in df.columns before writing."],"exampleFix":"// before\ndf.write_excel('out.xlsx', sparklines={'line': {'columns': ['q1', 'q3']}})\n// after\ndf = df.select(['q1', 'q2', 'q3'])  # ensure adjacency\ndf.write_excel('out.xlsx', sparklines={'line': {'columns': ['q1', 'q2', 'q3']}})","handlingStrategy":"validation","validationCode":"names = spark_cols\nidx = [df.columns.index(c) for c in names]\nassert all(idx[i+1] - idx[i] == 1 for i in range(len(idx)-1)), 'sparkline columns must be adjacent'","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Reorder/select columns contiguously before adding sparklines","Keep sparkline column lists derived from df.columns slices rather than hand-written names"],"tags":["excel","sparklines","polars","dataframe"],"backgroundTag":"invalid-argument-value","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}