Skip to main content
Glama
hyunjae-labs

xlwings Excel MCP Server

by hyunjae-labs

write_data_to_excel

Write structured data to Excel worksheets using the xlwings Excel MCP Server. Insert lists of data into specified cells or automatically find appropriate locations for data placement.

Instructions

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)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
session_idYes
sheet_nameYes
dataYes
start_cellNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Core handler function that executes the xlwings logic for writing data to an Excel sheet using an existing workbook session object.
    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)}"}
  • MCP tool registration and wrapper handler for 'write_data_to_excel'. Handles session validation, locking, imports the core impl, and returns formatted response.
    @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
  • Legacy helper function for writing data using filepath (not directly used by the MCP tool, but similar implementation without session).
    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}")

Schema Changelog

Changes observed during successful MCP inspections.

  1. Changed3 schema fields changed
    • removedInput schema / properties / filepath
      Removed value: -{
      -  "title": "Filepath",
      -  "type": "string"
      -}
    • addedInput schema / properties / session_id
      Added value: +{
      +  "title": "Session Id",
      +  "type": "string"
      +}
    • changedInput schema / required
      Previous value: -[
      -  "filepath",
      -  "sheet_name",
      -  "data"
      -]New value: +[
      +  "session_id",
      +  "sheet_name",
      +  "data"
      +]
  2. First observed

TDQS

B3.4/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

The description discloses that the tool writes 'without any verification,' which is a behavioral trait. However, it lacks details on overwriting behavior, error handling, or performance. With no annotations, more transparency is expected.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is relatively concise with a clear first sentence. The 'Args:' section is redundant but not verbose. Each sentence adds information without excess.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description covers all parameters but lacks context about return values, error conditions, and prerequisites beyond what is implied by parameters. An output schema exists but its content is not considered.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description adds meaning beyond the schema: explains session_id as 'from open_workbook', data as 'list of lists with sublists as rows', and start_cell as 'optional, auto-finds appropriate location'. Schema coverage is 0%, so this adds significant value.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Write data to') and the resource ('Excel worksheet'). It distinguishes from siblings like read_data_from_excel and create_workbook.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No explicit guidance on when to use this tool vs alternatives. The description implies writing data but does not mention prerequisites (e.g., must have an open workbook) or scenarios where other tools are preferred.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.