apply_formula
Apply Excel formulas to specific cells with verification. Works with xlwings Excel MCP Server for secure Excel file manipulation in corporate environments.
Instructions
Apply Excel formula to cell. Excel formula will write to cell with verification.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| cell | Yes | ||
| filepath | Yes | ||
| formula | Yes | ||
| sheet_name | Yes |
Input Schema (JSON Schema)
{
"properties": {
"cell": {
"title": "Cell",
"type": "string"
},
"filepath": {
"title": "Filepath",
"type": "string"
},
"formula": {
"title": "Formula",
"type": "string"
},
"sheet_name": {
"title": "Sheet Name",
"type": "string"
}
},
"required": [
"filepath",
"sheet_name",
"cell",
"formula"
],
"title": "apply_formulaArguments",
"type": "object"
}
Implementation Reference
- src/xlwings_mcp/server.py:232-265 (handler)The MCP tool handler for 'apply_formula'. Validates the session, acquires lock, imports and calls the xlwings implementation helper, and returns formatted result or error.@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
- The supporting utility function that performs the actual formula application using xlwings on an existing workbook object. Handles sheet validation, formula normalization, application, result retrieval, and saving.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)}"}