Skip to main content
Glama
hyunjae-labs

xlwings Excel MCP Server

by hyunjae-labs

apply_formula

Insert Excel formulas into specific worksheet cells using xlwings MCP server for automated spreadsheet calculations and data processing.

Instructions

Apply Excel formula to cell.

Args:
    session_id: Session ID from open_workbook (required)
    sheet_name: Name of worksheet
    cell: Cell address (e.g., "A1")
    formula: Excel formula to apply

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
session_idYes
sheet_nameYes
cellYes
formulaYes

Implementation Reference

  • Core implementation of the apply_formula tool logic for session-based workbook using xlwings. Applies formula to specified cell, normalizes it, calculates result, saves workbook, and returns detailed response.
    def apply_formula_xlw_with_wb(
        wb,
        sheet_name: str,
        cell: str,
        formula: str
    ) -> Dict[str, Any]:
        """Apply formula using existing workbook object (session-based).
        
        Args:
            wb: Workbook object from session
            sheet_name: Sheet name
            cell: Target cell (e.g., A1)
            formula: Formula to apply
            
        Returns:
            Dictionary with result and calculated value
        """
        try:
            # Check sheet exists
            if sheet_name not in [s.name for s in wb.sheets]:
                return {"error": f"Sheet '{sheet_name}' not found"}
            
            ws = wb.sheets[sheet_name]
            
            # Normalize formula
            if not formula.startswith('='):
                formula = f'={formula}'
            
            # Get cell
            cell_range = ws.range(cell)
            
            # Apply formula
            try:
                cell_range.formula = formula
            except Exception as e:
                return {
                    "error": f"Formula error in cell {cell}: {str(e)}",
                    "formula": formula,
                    "cell": cell
                }
            
            # Get calculated result
            try:
                calculated_value = cell_range.value
                display_value = cell_range.api.Text
            except Exception as e:
                logger.warning(f"Failed to read calculated value: {e}")
                calculated_value = None
                display_value = None
            
            # Save workbook
            wb.save()
            
            return {
                "message": f"Formula applied to {cell}",
                "cell": cell,
                "formula": formula,
                "calculated_value": calculated_value,
                "display_value": display_value
            }
            
        except Exception as e:
            logger.error(f"Failed to apply formula: {e}")
            return {"error": f"Failed to apply formula: {str(e)}"}
  • MCP tool registration using @mcp.tool() decorator. Defines input schema via parameters and docstring, validates session, calls the handler, and handles errors.
    @mcp.tool()
    def apply_formula(
        session_id: str,
        sheet_name: str,
        cell: str,
        formula: str
    ) -> str:
        """
        Apply Excel formula to cell.
        
        Args:
            session_id: Session ID from open_workbook (required)
            sheet_name: Name of worksheet
            cell: Cell address (e.g., "A1")
            formula: Excel formula to apply
        """
        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.calculations_xlw import apply_formula_xlw_with_wb
                result = apply_formula_xlw_with_wb(session.workbook, sheet_name, cell, formula)
            
            return result.get("message", "Formula applied successfully") if "error" not in result else f"Error: {result['error']}"
                
        except (ValidationError, CalculationError) as e:
            return f"Error: {str(e)}"
        except Exception as e:
            logger.error(f"Error applying formula: {e}")
            raise

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