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

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}")

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