Stefan Broenner 29adbb3b25 refactor: eliminate dead code and cargo cult patterns (-1,286 lines) (#334)
* refactor: eliminate cargo cult patterns in PivotTable and Range commands

- Create PivotTableHelpers class with centralized OLAP detection:
  - IsOlapPivotTable() - boolean check with COM cleanup
  - TryGetCubeFields() - returns cubeFields for subsequent operations

- Replace duplicated OLAP detection try-catch blocks across 8 files:
  - PivotTableCommands.Fields.cs
  - PivotTableCommands.Lifecycle.cs
  - PivotTableCommands.cs
  - PivotTableCommands.CalculatedMembers.cs
  - PivotTableCommands.CalculatedFields.cs
  - OlapPivotTableFieldStrategy.cs
  - RegularPivotTableFieldStrategy.cs
  - PivotTableFieldStrategyFactory.cs

- Fix nullable bool comparisons (== true -> is true):
  - RangeCommands.Validation.cs
  - OlapPivotTableFieldStrategy.cs (3 instances)
  - PowerQueryCommands.Helpers.cs

Fixes #333

* refactor: eliminate PivotTable strategy execution boilerplate

- Create ExecuteWithStrategy<TResult> helper method centralizing:
  - PivotTable lookup via CoreLookupHelpers.FindPivotTable
  - Strategy creation via PivotTableFieldStrategyFactory
  - Operation execution with proper COM cleanup in finally block

- Refactor 12 methods to use helper (expression-bodied):
  - Fields: AddRowField, AddColumnField, AddValueField, AddFilterField,
            RemoveField, SetFieldFunction, SetFieldName
  - Grouping: GroupByDate, GroupByNumeric
  - Layout: SetLayout, Subtotals: SetSubtotals, GrandTotals: SetGrandTotals
  - CalculatedFields: CreateCalculatedField
  - Analysis: SetFieldFilter, SortField

- Remove unused 'using Sbroenne.ExcelMcp.ComInterop' from 4 files
- Remove redundant null check in SetGrandTotals (FindPivotTable throws)

Methods kept as-is (require context access or complex logic):
- SetFieldFormat (needs ctx.FormatTranslator)
- ListFields, GetData (complex iteration/extraction logic)
- ListCalculatedFields, DeleteCalculatedField (OLAP-specific paths)

Reduction: ~150 lines of duplicate boilerplate eliminated

* refactor: eliminate redundant table null checks

- Change TableCommands.FindTable to call CoreLookupHelpers.FindTable
  (which throws) instead of TryFindTable (which returns null)

- Remove 22 redundant null checks across 9 TableCommands files:
  - Data.cs (2), Filters.cs (4), Lifecycle.cs (3)
  - NumberFormat.cs (2), Sort.cs (2), Structure.cs (4)
  - StructuredReferences.cs (1), Columns.cs (3), DataModel.cs (1)

- Same pattern fix as PivotTable strategy execution:
  FindTable now throws, so callers don't need to check+throw

Reduction: 88 lines of redundant null check boilerplate eliminated

* refactor: remove dead aggregation helpers and consolidate VBA type mapping

- Remove 3 unused methods from PivotTableCommands.cs (IsValidAggregationForDataType,
  GetValidAggregationsForDataType, GetComAggregationFunction)
- Remove 1 unused method from OlapPivotTableFieldStrategy.cs (GetComAggregationFunction)
- Add GetVbaModuleTypeName() helper to VbaCommands.cs
- Replace 2 inline switch expressions with helper in VbaCommands.Lifecycle.cs

Net reduction: 71 lines (17+/88-)

* refactor: consolidate GetAreaName into PivotTableHelpers

- Add GetAreaName() to PivotTableHelpers.cs as shared utility
- Remove duplicated GetAreaName() from PivotTableCommands.cs (dead code)
- Remove duplicated GetAreaName() from OlapPivotTableFieldStrategy.cs
- Remove duplicated GetAreaName() from RegularPivotTableFieldStrategy.cs
- Update all 8 usages to use PivotTableHelpers.GetAreaName()

Net reduction: 27 lines (26+/53-)

* refactor: consolidate GetAggregationFunctionFromCom into PivotTableHelpers

* refactor: consolidate DetectFieldDataType into PivotTableHelpers

- Move DetectFieldDataType from PivotTableCommands and RegularPivotTableFieldStrategy to PivotTableHelpers
- Update 8 usages across 4 files to use centralized helper
- Eliminates ~50 lines of duplicated data type detection logic

* refactor: consolidate GetFieldUniqueValues into PivotTableHelpers

- Add GetFieldUniqueValues to PivotTableHelpers (identical logic)
- Remove dead code from PivotTableCommands.cs (method was defined but never called)
- Remove duplicate from RegularPivotTableFieldStrategy.cs
- Update 3 callers to use centralized helper
- Eliminates ~40 lines of duplicated/dead code

* refactor: consolidate ParseColor and ParseBorderStyle into FormattingHelpers

* refactor: remove dead WithSessionAsync method

* refactor: remove dead code (-937 lines)

Removed unused code across all layers:

Core:
- IsValidTableName (TableCommands.cs) - never called
- CreatePowerQueryPipeline, PowerQueryConfig, POWER_QUERY_DATA_MODEL_ERROR (ResiliencePipelines.cs)
- RemoveQueryTablesFromSheet, CreateQueryTable (PowerQueryHelpers.cs)
- RemoveQueryConnections, CreateQueryTableConnection, SetQueryLoadToDataModel, CheckQueryDataModelConfiguration (PowerQueryCommands.Helpers.cs)
- GetConnectionNames, RemoveConnections (ConnectionHelpers.cs)
- ExcelConstants.cs - entire file never referenced

ComInterop:
- SpinWaitDelayMs, XlExcel12Binary constants

MCP Server:
- style_names.md, powerquery_targetCellAddress.md - completion files never loaded
- excel_datamodel.md - prompt content never wired up (info already in tool description)

Tests:
- CreateMultipleConnections (ConnectionTestHelper.cs)

* refactor: remove dead completion handler infrastructure (-349 lines)

Removed ExcelCompletionHandler.cs and supporting files which were
written but never wired up to the MCP server (HandleCompletion never called).

Deleted files:
- ExcelCompletionHandler.cs (178 lines) - never registered with MCP
- 7 completion markdown files (border_styles, border_weights, load_destination,
  privacy_level, table_styles, validation_operators, validation_types)

Also cleaned up:
- Removed LoadCompletion/LoadCompletionValues from MarkdownLoader.cs
- Removed unused ListEmbeddedResources debugging method
- Updated mcp-llm-guidance.instructions.md to reflect actual status

* fix: suppress CA1031 warnings for intentional COM interop patterns

---------

Co-authored-by: Stefan Broenner <stefan.broenner@microsoft.comm>
2025-12-25 11:26:30 +01:00
2025-12-09 10:47:13 +00:00
2025-11-17 09:27:59 +00:00

ExcelMcp - MCP Server for Microsoft Excel

VS Code Marketplace Installs Downloads NuGet Downloads - MCP Server

Build MCP Server Build CLI Release NuGet MCP Server NuGet CLI

License: MIT .NET Platform Built with Copilot

Automate Excel with AI - A Model Context Protocol (MCP) server for comprehensive Excel automation through conversational AI.

MCP Server for Excel enables AI assistants (GitHub Copilot, Claude, ChatGPT) to automate Excel through natural language commands. Automate Power Query, DAX measures, VBA macros, PivotTables, Charts, formatting, and data transformations (12 tools with 182 operations).

🛡️ 100% Safe - Uses Excel's Native COM API - Zero risk of file corruption. Unlike third-party libraries that manipulate .xlsx files directly, this project uses Excel's official API ensuring complete safety and compatibility.

💡 Interactive Development - See results instantly in Excel. Create a query, run it, inspect the output, refine and repeat. Excel becomes your AI-powered workspace for rapid development and testing.

Optional CLI Tool: For advanced users who prefer command-line scripting, ExcelMcp includes a CLI interface for RPA workflows, CI/CD pipelines, and batch automation.

🚀 Quick Start (1 Minute)

Requirements: Windows OS + Microsoft Excel 2016+

Fastest way to get started - everything configured automatically: Install from Marketplace

The extension opens automatically after installation with a quick start guide!

For Visual Studio, Claude Desktop, Cursor, Windsurf, or other MCP clients:

📖 Complete Installation Guide → - Step-by-step setup for all AI assistants with ready-to-use config files

⚠️ Important: Close all Excel files before using ExcelMcp. The server requires exclusive access to workbooks during automation (Excel COM limitation).

🎯 What You Can Do

12 specialized tools with 182 operations:

  • 🔄 Power Query (9 ops) - Atomic workflows, M code management, load destinations
  • 📊 Data Model/DAX (16 ops) - Measures, relationships, model structure
  • 🎨 Excel Tables (24 ops) - Lifecycle, filtering, sorting, structured references
  • 📈 PivotTables (30 ops) - Creation, fields, aggregations, calculated members/fields
  • 📉 Charts (14 ops) - Create, configure, manage series and formatting
  • 📝 VBA (6 ops) - Modules, execution, version control
  • 📋 Ranges (42 ops) - Values, formulas, formatting, validation, protection
  • 📄 Worksheets (16 ops) - Lifecycle, colors, visibility, cross-workbook moves
  • 🔌 Connections (9 ops) - OLEDB/ODBC management and refresh
  • 🏷️ Named Ranges (6 ops) - Parameters and configuration
  • 📁 Files (6 ops) - Session management and workbook creation
  • 🎨 Conditional Formatting (2 ops) - Rules and clearing

📚 Complete Feature Reference → - Detailed documentation of all 182 operations

💬 Example Prompts

Data Transformation & Analysis:

  • "Optimize all my Power Queries in this workbook for better performance"
  • "Create a PivotTable from SalesData table showing top 10 products by region with sum and average"
  • "Create a data model from the following tables ... "
  • "Build a DAX measure calculating year-over-year growth with proper time intelligence"
  • "Filter this table by Column Product = Sushi"
  • *"Create a treemap chart from this table".

Formatting & Styling (No Programming Required):

  • "Format the revenue columns as currency, make headers bold with blue background, and add borders to the table"
  • "Apply conditional formatting to highlight values above $10,000 in red and below $5,000 in yellow"
  • "Convert this data range to an Excel Table with style TableStyleMedium2, add auto-filters, and create a totals row"

Workflow Automation:

  • "Find all cells containing 'Q1 2024' and replace with 'Q1 2025', then sort the table by Date descending"
  • "Add data validation dropdowns to the Status column with options: Active, Pending, Completed"
  • "Merge the header cells, center-align them, and auto-fit all column widths to content"

👥 Who Should Use This?

Perfect for:

  • ✅ Data analysts automating repetitive Excel workflows
  • ✅ Developers building Excel-based data solutions
  • ✅ Business users managing complex Excel workbooks
  • ✅ Teams maintaining Power Query/VBA/DAX code in Git

Not suitable for:

  • ❌ Server-side data processing (use libraries like ClosedXML, EPPlus instead)
  • ❌ Linux/macOS users (Windows + Excel installation required)
  • ❌ High-volume batch operations (consider Excel-free alternatives)

📋 Additional Information

CLI for Direct Automation

xcelMcp includes a CLI interface for Excel automation without AI assistance. This is useful for RPA workflows, CI/CD pipelines, or batch processing scripts. Run excelcli --help for a categorized list of commands, or excelcli sheet --help (replace sheet) to view action-specific options. Always follow the session pattern: excelcli session open <file> → run commands with --session <id> → excelcli session save/close <id>. See CLI Guide for complete documentation.

🔧 How It Works - COM Interop Architecture

ExcelMcp uses Windows COM automation to control the actual Excel application (not just .xlsx files).

This means you get:

  • ✅ Full Excel Feature Access - Power Query engine, VBA runtime, Data Model, calculation engine, pivot tables
  • ✅ True Compatibility - Works exactly like Excel UI, no feature limitations
  • ✅ Live Data Operations - Refresh Power Query, connections, Data Model in real workbooks
  • ✅ Interactive Development - Immediate Excel feedback as AI makes changes
  • ✅ All File Formats - .xlsx, .xlsm, .xlsb, even legacy formats

💡 Tip: Watch Excel While AI Works By default, Excel runs hidden for faster automation. To see changes in real-time, just ask:

  • "Show me Excel while you work"
  • "Let me watch what you're doing"
  • "Open Excel so I can see the changes"

The AI will display the Excel window so you can watch every operation happen live - great for learning or verifying changes!

Technical Requirements:

  • ⚠️ Windows Only - COM interop is Windows-specific
  • ⚠️ Excel Required - Microsoft Excel 2016 or later must be installed
  • ⚠️ Desktop Environment - Controls actual Excel process (not for server-side processing)

📚 Complete MCP Server Guide → - Detailed tool documentation and examples

Project Information

License: MIT License - see LICENSE file

Contributing: See CONTRIBUTING.md for guidelines

Built With: This entire project was developed using GitHub Copilot AI assistance - mainly with Claude but lately with Auto-mode.

Acknowledgments:

  • Microsoft Excel Team - For comprehensive COM automation APIs
  • Model Context Protocol community - For the AI integration standard
  • Open Source Community - For inspiration and best practices

SEO & Discovery

Excel Automation • Automate Excel with AI • MCP Server • Model Context Protocol • GitHub Copilot Excel • AI Excel Assistant • Power Query Automation • Power Query M Code • Power Pivot Automation • DAX Measures • DAX Automation • Data Model Automation • PivotTable Automation • VBA Automation • Excel Tables Automation • Excel AI Integration • COM Interop • Windows Excel Automation • Excel Development Tools • Excel Productivity • Excel Scripting • Conversational Excel • Natural Language Excel

S
Description
Excel MCP Server skill for Windows workbook automation. Use when an assistant needs rich MCP tools to create, inspect, modify, format, or analyze Excel files.…
Readme MIT 23 MiB
Languages
C# 88.8%
PowerShell 6.5%
Python 3.2%
HTML 0.8%
JavaScript 0.3%
Other 0.3%