apply_formula
Apply an Excel formula to a specified cell with verification, ensuring accurate data manipulation in a workbook. Input filepath, sheet name, cell, and formula for precise execution.
Instructions
Apply Excel formula to cell. Excel formula will write to cell with verification.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| cell | Yes | ||
| filepath | Yes | ||
| formula | Yes | ||
| sheet_name | Yes |
Implementation Reference
- src/excel_mcp/server.py:95-122 (handler)MCP tool registration and handler for 'apply_formula'. Validates input then delegates to core implementation.@mcp.tool() def apply_formula( filepath: str, sheet_name: str, cell: str, formula: str, ) -> str: """ Apply Excel formula to cell. Excel formula will write to cell with verification. """ try: full_path = get_excel_path(filepath) # First validate the formula validation = validate_formula_impl(full_path, sheet_name, cell, formula) if isinstance(validation, dict) and "error" in validation: return f"Error: {validation['error']}" # If valid, apply the formula from excel_mcp.calculations import apply_formula as apply_formula_impl result = apply_formula_impl(full_path, sheet_name, cell, formula) return result["message"] except (ValidationError, CalculationError) as e: return f"Error: {str(e)}" except Exception as e: logger.error(f"Error applying formula: {e}") raise
- src/excel_mcp/calculations.py:11-60 (helper)Core helper function that loads workbook, applies formula to cell, validates syntax, and saves the file.def apply_formula( filepath: str, sheet_name: str, cell: str, formula: str ) -> dict[str, Any]: """Apply any Excel formula to a cell.""" try: if not validate_cell_reference(cell): raise ValidationError(f"Invalid cell reference: {cell}") wb = get_or_create_workbook(filepath) if sheet_name not in wb.sheetnames: raise ValidationError(f"Sheet '{sheet_name}' not found") sheet = wb[sheet_name] # Ensure formula starts with = if not formula.startswith('='): formula = f'={formula}' # Validate formula syntax is_valid, message = validate_formula(formula) if not is_valid: raise CalculationError(f"Invalid formula syntax: {message}") try: # Apply formula to the cell cell_obj = sheet[cell] cell_obj.value = formula except Exception as e: raise CalculationError(f"Failed to apply formula to cell: {str(e)}") try: wb.save(filepath) except Exception as e: raise CalculationError(f"Failed to save workbook after applying formula: {str(e)}") return { "message": f"Applied formula '{formula}' to cell {cell}", "cell": cell, "formula": formula } except (ValidationError, CalculationError) as e: logger.error(str(e)) raise except Exception as e: logger.error(f"Failed to apply formula: {e}") raise CalculationError(str(e))