create_workbook
Create a new Excel workbook in the xlwings Excel MCP Server. Use session_id for optimal performance when working within existing sessions.
Instructions
Create new Excel workbook.
Args:
session_id: Session ID for creating workbook in existing session (optional)
filepath: Path to create new Excel file (legacy, deprecated)
Note: Use session_id for better performance. filepath parameter is deprecated.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| session_id | No | ||
| filepath | No |
Implementation Reference
- src/xlwings_mcp/server.py:504-547 (handler)Primary MCP tool handler and registration for 'create_workbook'. Handles both session-based (preferred) and legacy filepath modes by delegating to implementation helpers.def create_workbook( session_id: Optional[str] = None, filepath: Optional[str] = None ) -> str: """ Create new Excel workbook. Args: session_id: Session ID for creating workbook in existing session (optional) filepath: Path to create new Excel file (legacy, deprecated) Note: Use session_id for better performance. filepath parameter is deprecated. """ try: # Support both new (session_id) and old (filepath) API if session_id: # New API: use session (though this is less common for creating new workbooks) session = SESSION_MANAGER.get_session(session_id) if not session: return f"Error: Session {session_id} not found. Please open the workbook first using open_workbook()." with session.lock: from xlwings_mcp.xlwings_impl.workbook_xlw import create_workbook_xlw_with_wb result = create_workbook_xlw_with_wb(session.workbook) return result.get("message", "Workbook created successfully") if "error" not in result else f"Error: {result['error']}" elif filepath: # Legacy API: backwards compatibility logger.warning("Using deprecated filepath parameter. Please use session_id instead.") full_path = get_excel_path(filepath) from xlwings_mcp.workbook import create_workbook as create_workbook_impl create_workbook_impl(full_path) return f"Created workbook at {full_path}" else: return ERROR_TEMPLATES['PARAMETER_MISSING'].format( param1='session_id', param2='filepath' ) except WorkbookError as e: return f"Error: {str(e)}" except Exception as e: logger.error(f"Error creating workbook: {e}") raise
- src/xlwings_mcp/workbook.py:13-18 (helper)Legacy wrapper function called by the main handler for filepath mode. Delegates to xlwings-specific implementation.def create_workbook(filepath: str, sheet_name: str = "Sheet1") -> dict[str, Any]: """Create a new Excel workbook with optional custom sheet name""" result = create_workbook_xlw(filepath, sheet_name) if "error" in result: raise WorkbookError(result["error"]) return result
- Core xlwings implementation for creating a new workbook using excel_context context manager. Called by legacy wrapper.def create_workbook_xlw( filepath: str, sheet_name: Optional[str] = None ) -> Dict[str, Any]: """xlwings를 사용한 새 워크북 생성 Args: filepath: 생성할 파일 경로 sheet_name: 기본 시트명 (optional, defaults to Excel's default) Returns: 생성 결과 딕셔너리 """ try: # Use Excel's default sheet name if not provided if not sheet_name: sheet_name = "Sheet1" # Excel's default # Excel context로 새 워크북 생성 with excel_context(filepath, create_if_not_exists=True, sheet_name=sheet_name) as wb: # 워크북이 이미 저장되었으므로 추가 작업 없음 return { "message": f"Created workbook: {filepath}", "filepath": filepath, "active_sheet": sheet_name } except Exception as e: logger.error(f"xlwings 워크북 생성 실패: {e}") return {"error": f"Failed to create workbook: {str(e)}"}
- Session-based xlwings helper for configuring an existing workbook object (used by main handler in session mode).def create_workbook_xlw_with_wb(wb, sheet_name: Optional[str] = None) -> Dict[str, Any]: """Session-based version using existing workbook object. Args: wb: Workbook object from session sheet_name: 기본 시트명 (optional, defaults to Excel's default) Returns: 생성 결과 딕셔너리 """ try: # This is a special case - when wb is provided, we might add sheets or modify it # For a new workbook, typically the workbook creation was handled in session setup # But we can still configure it here if sheet_name and wb.sheets: # Rename the first sheet if sheet_name is provided first_sheet = wb.sheets[0] if first_sheet.name != sheet_name: first_sheet.name = sheet_name # Save the workbook to ensure changes persist wb.save() return { "message": f"Workbook configured successfully", "active_sheet": wb.sheets[0].name if wb.sheets else None, "sheet_count": len(wb.sheets) } except Exception as e: logger.error(f"xlwings 워크북 설정 실패: {e}") return {"error": f"Failed to configure workbook: {str(e)}"}