Skip to main content
Glama
hyunjae-labs

xlwings Excel MCP Server

by hyunjae-labs

write_data_to_excel

Write structured data to an Excel worksheet with specified file path, sheet name, and starting cell. Supports direct data insertion without verification for efficient worksheet updates.

Instructions

Write data to Excel worksheet. Excel formula will write to cell without any verification. PARAMETERS: filepath: Path to Excel file sheet_name: Name of worksheet to write to data: List of lists containing data to write to the worksheet, sublists are assumed to be rows start_cell: Cell to start writing to (optional, auto-finds appropriate location)

Input Schema

NameRequiredDescriptionDefault
dataYes
filepathYes
sheet_nameYes
start_cellNo

Input Schema (JSON Schema)

{ "properties": { "data": { "items": { "items": {}, "type": "array" }, "title": "Data", "type": "array" }, "filepath": { "title": "Filepath", "type": "string" }, "sheet_name": { "title": "Sheet Name", "type": "string" }, "start_cell": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null, "title": "Start Cell" } }, "required": [ "filepath", "sheet_name", "data" ], "title": "write_data_to_excelArguments", "type": "object" }

Implementation Reference

  • Main handler for 'write_data_to_excel' tool: validates session, acquires lock, imports and calls the xlwings implementation, handles errors and returns result message.
    @mcp.tool() def write_data_to_excel( session_id: str, sheet_name: str, data: List[List], start_cell: Optional[str] = None ) -> str: """ Write data to Excel worksheet. Excel formula will write to cell without any verification. Args: session_id: Session ID from open_workbook (required) sheet_name: Name of worksheet to write to data: List of lists containing data to write to the worksheet, sublists are assumed to be rows start_cell: Cell to start writing to (optional, auto-finds appropriate location) """ try: # Validate session using centralized helper session = get_validated_session(session_id) if isinstance(session, str): # Error message returned return session with session.lock: from xlwings_mcp.xlwings_impl.data_xlw import write_data_to_excel_xlw_with_wb result = write_data_to_excel_xlw_with_wb(session.workbook, sheet_name, data, start_cell) return result.get("message", "Data written successfully") if "error" not in result else f"Error: {result['error']}" except (ValidationError, DataError) as e: return f"Error: {str(e)}" except Exception as e: logger.error(f"Error writing data: {e}") raise
  • Core xlwings implementation for writing data to a worksheet in an open workbook session. Handles sheet creation, auto-locates start cell, writes data using range.value, saves workbook.
    def write_data_to_excel_xlw_with_wb( wb, sheet_name: str, data: List[List], start_cell: Optional[str] = None ) -> Dict[str, str]: """xlwings 세션 기반 데이터 쓰기 Args: wb: 워크북 객체 (세션에서 전달) sheet_name: 시트명 data: 쓸 데이터 (2차원 리스트) start_cell: 시작 셀 (기본값: A1) Returns: 작업 결과 메시지 딕셔너리 """ try: # 데이터 검증 if not data: return {"error": "No data provided to write"} # 시트 확인/생성 sheet_names = [s.name for s in wb.sheets] if sheet_name not in sheet_names: wb.sheets.add(sheet_name) ws = wb.sheets[sheet_name] # Set default start_cell if not provided if not start_cell: # Find appropriate location for writing used_range = ws.used_range if used_range: # If sheet has data, find empty area below it last_row = used_range.last_cell.row start_cell = f"A{last_row + 2}" # Leave one row gap else: start_cell = "A1" # 데이터 쓰기 (성능 최적화를 위해 calc_state_context 사용) with ExcelHelper.calc_state_context(wb): range_obj = ws.range(start_cell) range_obj.value = data # 파일 저장 wb.save() return {"message": f"Data written to {sheet_name} starting from {start_cell}"} except Exception as e: logger.error(f"xlwings 데이터 쓰기 실패: {e}") return {"error": f"Failed to write data: {str(e)}"}
  • Standalone (non-session) xlwings implementation for writing data to Excel file. Opens/creates workbook, handles resources, similar logic to with_wb version.
    def write_data_to_excel_xlw( filepath: str, sheet_name: str, data: List[List], start_cell: Optional[str] = None ) -> Dict[str, str]: """xlwings를 사용한 데이터 쓰기 Args: filepath: Excel 파일 경로 sheet_name: 시트명 data: 쓸 데이터 (2차원 리스트) start_cell: 시작 셀 (기본값: A1) Returns: 작업 결과 메시지 딕셔너리 """ app = None wb = None # Initialize COM for thread safety (Windows) _com_initialize() try: # 데이터 검증 if not data: return {"error": "No data provided to write"} # Excel 앱 시작 app = xw.App(visible=False, add_book=False) # 파일이 존재하는지 확인 if os.path.exists(filepath): wb = app.books.open(filepath) else: # 파일이 없으면 새로 생성 wb = app.books.add() # 디렉토리 생성 Path(filepath).parent.mkdir(parents=True, exist_ok=True) wb.save(filepath) # 시트 확인/생성 sheet_names = [s.name for s in wb.sheets] if sheet_name not in sheet_names: wb.sheets.add(sheet_name) ws = wb.sheets[sheet_name] # Set default start_cell if not provided if not start_cell: # Find appropriate location for writing used_range = ws.used_range if used_range: # If sheet has data, find empty area below it last_row = used_range.last_cell.row start_cell = f"A{last_row + 2}" # Leave one row gap else: start_cell = "A1" # 데이터 쓰기 range_obj = ws.range(start_cell) range_obj.value = data # 파일 저장 wb.save() return {"message": f"Data written to {sheet_name} starting from {start_cell}"} except Exception as e: logger.error(f"xlwings 데이터 쓰기 실패: {e}") return {"error": f"Failed to write data: {str(e)}"} finally: # 리소스 정리 if wb: try: wb.close() except Exception as e: logger.warning(f"워크북 닫기 실패: {e}") if app: try: app.quit() except Exception as e: logger.warning(f"Excel 앱 종료 실패: {e}")

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/hyunjae-labs/xlwings-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server