copy_sheet
Duplicate a sheet within the same spreadsheet workbook, copying all cell values to create a new sheet with an optional custom name and position.
Instructions
Duplicate a sheet within the same workbook.
Copies all cell values. Returns the name of the new sheet. Not supported for CSV files.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| file | Yes | Path to the spreadsheet file | |
| source_name | Yes | Name of the existing sheet to duplicate | |
| new_name | No | Name for the copy. Auto-generated if omitted. | |
| position | No | 1-based position for the copied sheet. Placed at the end if omitted. |
Implementation Reference
- The MCP tool registration and handler function for `copy_sheet`. It takes the file path, source sheet name, and optional new name/position parameters, performs the copy via the backend, and saves the workbook.
@mcp.tool() def copy_sheet( file: Annotated[str, Field(description="Path to the spreadsheet file")], source_name: Annotated[str, Field(description="Name of the existing sheet to duplicate")], new_name: Annotated[str | None, Field(description="Name for the copy. Auto-generated if omitted.")] = None, position: Annotated[int | None, Field(description="1-based position for the copied sheet. Placed at the end if omitted.")] = None, ) -> str: """Duplicate a sheet within the same workbook. Copies all cell values. Returns the name of the new sheet. Not supported for CSV files. """ wb = load_workbook(file) copied = wb.copy_sheet(source_name) if new_name: copied.title = new_name if position is not None: current_idx = wb.sheetnames.index(copied.title) wb.move_sheet(copied, offset=position - 1 - current_idx) wb.save(file) return copied.title # --------------------------------------------------------------------------- - The backend implementation for copying a sheet in XLSX files using openpyxl's `copy_worksheet` method.
def copy_sheet(self, source_name: str) -> XlsxSheet: if source_name not in self._wb.sheetnames: raise ValueError(f"Sheet not found: {source_name!r}") copied = self._wb.copy_worksheet(self._wb[source_name]) return XlsxSheet(copied)