update_excel
Modify existing Excel files by adding or replacing data in specified sheets using CSV or JSON formats. Automate file updates efficiently with clear input parameters.
Instructions
Update an existing Excel file with new data.
Args:
file_path: Path to the Excel file to update
data: New data in CSV or JSON format
sheet_name: Name of the sheet to update (for Excel files)
format: Format of the input data ('csv' or 'json')
Returns:
Confirmation message
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| data | Yes | ||
| file_path | Yes | ||
| format | No | csv | |
| sheet_name | No | Sheet1 |
Implementation Reference
- mcp_excel_server/server.py:253-309 (handler)The handler function for the 'update_excel' MCP tool. It updates an existing Excel (.xlsx, .xls, .xlsm), CSV, TSV, or JSON file with new data provided as a string in CSV or JSON format. For multi-sheet Excel files, it preserves other sheets and replaces the specified sheet.@mcp.tool() def update_excel(file_path: str, data: str, sheet_name: Optional[str] = "Sheet1", format: Optional[str] = "csv") -> str: """ Update an existing Excel file with new data. Args: file_path: Path to the Excel file to update data: New data in CSV or JSON format sheet_name: Name of the sheet to update (for Excel files) format: Format of the input data ('csv' or 'json') Returns: Confirmation message """ try: # Check if file exists if not os.path.exists(file_path): return f"File not found: {file_path}" # Load new data if format.lower() == 'csv': new_df = pd.read_csv(io.StringIO(data)) elif format.lower() == 'json': new_df = pd.read_json(io.StringIO(data)) else: return f"Unsupported data format: {format}" # Get file extension _, ext = os.path.splitext(file_path) ext = ext.lower() # Read existing file if ext in ['.xlsx', '.xls', '.xlsm']: # For Excel files, we need to read all sheets excel_file = pd.ExcelFile(file_path) with pd.ExcelWriter(file_path) as writer: # Copy all existing sheets for sheet in excel_file.sheet_names: if sheet != sheet_name: df = pd.read_excel(excel_file, sheet_name=sheet) df.to_excel(writer, sheet_name=sheet, index=False) # Write new data to specified sheet new_df.to_excel(writer, sheet_name=sheet_name, index=False) elif ext == '.csv': new_df.to_csv(file_path, index=False) elif ext == '.tsv': new_df.to_csv(file_path, sep='\t', index=False) elif ext == '.json': new_df.to_json(file_path, orient='records') else: return f"Unsupported file extension: {ext}" return f"Successfully updated {file_path}" except Exception as e: return f"Error updating file: {str(e)}"