{"record":{"id":"aa44401d7b9572f7","repo":"PHPOffice/PhpSpreadsheet","slug":"workbook-already-contains-a-worksheet-named-wor","errorCode":null,"errorMessage":"Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename this worksheet first.","messagePattern":"Workbook already contains a worksheet named '(.+?)'\\. Rename this worksheet first\\.","errorType":"exception","errorClass":"PhpOffice\\PhpSpreadsheet\\Exception","httpStatus":null,"severity":"error","filePath":"src/PhpSpreadsheet/Spreadsheet.php","lineNumber":631,"sourceCode":"     * @param Worksheet $worksheet The worksheet to add\n     * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)\n     */\n    public function addSheet(Worksheet $worksheet, ?int $sheetIndex = null, bool $retitleIfNeeded = false): Worksheet\n    {\n        if ($retitleIfNeeded) {\n            $title = $worksheet->getTitle();\n            if ($this->sheetNameExists($title)) {\n                $i = 1;\n                $newTitle = \"$title $i\";\n                while ($this->sheetNameExists($newTitle)) {\n                    ++$i;\n                    $newTitle = \"$title $i\";\n                }\n                $worksheet->setTitle($newTitle);\n            }\n        }\n        if ($this->sheetNameExists($worksheet->getTitle())) {\n            throw new Exception(\n                \"Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename this worksheet first.\"\n            );\n        }\n\n        if ($sheetIndex === null) {\n            if ($this->activeSheetIndex < 0) {\n                $this->activeSheetIndex = 0;\n            }\n            $this->workSheetCollection[] = $worksheet;\n        } else {\n            // Insert the sheet at the requested index\n            array_splice(\n                $this->workSheetCollection,\n                $sheetIndex,\n                0,\n                [$worksheet]\n            );\n","sourceCodeStart":613,"sourceCodeEnd":649,"githubUrl":"https://github.com/PHPOffice/PhpSpreadsheet/blob/65b080eef4d9fd11a5796135ab145883e5c3d6a6/src/PhpSpreadsheet/Spreadsheet.php#L613-L649","documentation":"Spreadsheet::addSheet() inserts a Worksheet into the workbook and enforces unique sheet titles. Auto-renaming only happens when you pass the third argument $retitleIfNeeded = true (as duplicateWorksheetByTitle() does); by default a colliding title throws. Sheet titles are the workbook's key namespace, so duplicates would corrupt the file on save.","triggerScenarios":"Calling $spreadsheet->addSheet($sheet) where $sheet->getTitle() already matches a sheet in that workbook: e.g. addSheet(new Worksheet($spreadsheet, 'Report')) while 'Report' exists; re-adding a sheet you removed earlier without renaming; inserting a sheet built from a template with a fixed title into the same workbook twice.","commonSituations":"Template-based generators that stamp a constant name like 'Data' or 'Sheet1' per iteration; merging two workbooks sheet-by-sheet with addSheet() instead of addExternalSheet(); loops that create sheets from user-supplied names without uniquifying.","solutions":["Check uniqueness first: if ($spreadsheet->sheetNameExists($title)) pick another title before addSheet().","Pass true as the third argument: $spreadsheet->addSheet($sheet, null, true) to auto-rename to 'Title 1', 'Title 2', ...","Rename the incoming sheet before adding: $sheet->setTitle($uniqueTitle);","Rename or remove the pre-existing sheet: $spreadsheet->removeSheetByIndex($spreadsheet->getIndex($existingSheet));"],"exampleFix":"// before\n$spreadsheet->addSheet($sheet); // throws if 'Report' exists\n\n// after\nif ($spreadsheet->sheetNameExists($sheet->getTitle())) {\n    $sheet->setTitle($sheet->getTitle() . ' ' . uniqid());\n}\n$spreadsheet->addSheet($sheet);\n// or simply: $spreadsheet->addSheet($sheet, null, true);","handlingStrategy":"validation","validationCode":"if ($spreadsheet->sheetNameExists($sheet->getTitle())) {\n    $sheet->setTitle(uniqueTitle($sheet->getTitle(), $spreadsheet));\n}\n$spreadsheet->addSheet($sheet);\n\nfunction uniqueTitle(string $base, \\PhpOffice\\PhpSpreadsheet\\Spreadsheet $s): string\n{\n    $i = 1;\n    while ($s->sheetNameExists(\"$base $i\")) { ++$i; }\n    return \"$base $i\";\n}","typeGuard":"function canAddSheetWithTitle(\\PhpOffice\\PhpSpreadsheet\\Spreadsheet $s, string $title): bool\n{\n    return !$s->sheetNameExists($title);\n}","tryCatchPattern":"try {\n    $spreadsheet->addSheet($sheet);\n} catch (\\PhpOffice\\PhpSpreadsheet\\Exception $e) {\n    $sheet->setTitle($sheet->getTitle() . ' ' . uniqid());\n    $spreadsheet->addSheet($sheet);\n}","preventionTips":["Always uniquify generated titles (append date/source/timestamp).","Prefer createSheet() for blank sheets — it integrates with naming flow.","Pass true as the third argument to addSheet() to opt into auto-renaming."],"tags":["worksheet","duplicate-name","addsheet","phpspreadsheet"],"backgroundTag":"duplicate-sheet-name","analyzedSha":"65b080eef4d9fd11a5796135ab145883e5c3d6a6","analyzedAt":"2026-08-17T05:40:41.646Z","schemaVersion":2},"datasetVersion":"2026-08-17T09:17:11.063Z"}