{"record":{"id":"985cee5676f35e53","repo":"pola-rs/polars","slug":"no-matching-sheet-found-when-sheet-id-is-idx","errorCode":null,"errorMessage":"no matching sheet found when `sheet_id` is {idx}","messagePattern":"no matching sheet found when `sheet_id` is (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/io/spreadsheet/functions.py","lineNumber":829,"sourceCode":"            (sheet_name,) if isinstance(sheet_name, str) else sheet_name or ()\n        ):\n            known_sheet_names = {ws[\"name\"] for ws in worksheets}\n            for name in names:\n                if name not in known_sheet_names:\n                    msg = f\"no matching sheet found when `sheet_name` is {name!r}\"\n                    raise ValueError(msg)\n                sheet_names.append(name)\n        else:\n            ids = (sheet_id,) if isinstance(sheet_id, int) else sheet_id or ()\n            sheet_names_by_idx = {\n                idx: ws[\"name\"]\n                for idx, ws in enumerate(worksheets, start=1)\n                if (sheet_id == 0 or ws[\"index\"] in ids or ws[\"name\"] in names)\n            }\n            for idx in ids:\n                if (name := sheet_names_by_idx.get(idx)) is None:\n                    msg = f\"no matching sheet found when `sheet_id` is {idx}\"\n                    raise ValueError(msg)\n                sheet_names.append(name)\n\n    return sheet_names, return_multiple_sheets  # type: ignore[return-value]\n\n\ndef _initialise_spreadsheet_parser(\n    engine: str | None,\n    source: str | IO[bytes] | bytes,\n    engine_options: dict[str, Any],\n) -> tuple[Callable[..., pl.DataFrame], Any, list[dict[str, Any]]]:\n    \"\"\"Instantiate the indicated spreadsheet parser and establish related properties.\"\"\"\n    if isinstance(source, str) and not Path(source).exists():\n        raise FileNotFoundError(source)\n\n    if engine == \"xlsx2csv\":  # default\n        xlsx2csv = import_optional(\"xlsx2csv\")\n\n        # establish sensible defaults for unset options","sourceCodeStart":811,"sourceCodeEnd":847,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/io/spreadsheet/functions.py#L811-L847","documentation":"When selecting sheets by `sheet_id` (1-based index), `_get_sheet_names` looks each id up among available worksheets and raises a `ValueError` if an id has no matching sheet (e.g. beyond the sheet count, or id=0 which is invalid here).","triggerScenarios":"`pl.read_excel(f, sheet_id=5)` on a 3-sheet workbook; `sheet_id=[1, 4]` where 4 doesn't exist; `sheet_id=0`, which never matches a worksheet index.","commonSituations":"Hardcoded sheet positions after the workbook gained/lost sheets; assuming 0-based indexing when ids are 1-based; looping over a range larger than the sheet count.","solutions":["Use a valid 1-based id within the sheet count (check len of sheets first)","Use `sheet_name` if positions are unstable","Clamp/validate ids in a list before passing them"],"exampleFix":"// before\npl.read_excel(f, sheet_id=0)\n// after\npl.read_excel(f, sheet_id=1)","handlingStrategy":"validation","validationCode":"n_sheets = len(sheets)\nassert all(1 <= i <= n_sheets for i in ids), f'sheet_id must be 1..{n_sheets}'","typeGuard":null,"tryCatchPattern":"try:\n    df = pl.read_excel(f, sheet_id=sid)\nexcept ValueError as e:\n    if 'no matching sheet found' in str(e):\n        df = pl.read_excel(f, sheet_id=1)\n    else:\n        raise","preventionTips":["Remember sheet_id is 1-based, never 0","Clamp ids against the actual sheet count","Resolve sheets by name when the layout is unstable"],"tags":["python","polars","excel","sheet-id","index"],"backgroundTag":"value-out-of-range","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"}