Skip to main content
Glama
zhiwei5576

Excel MCP Server

by zhiwei5576

analyzeExcelStructure

Extract sheet names and column headers from Excel files to understand data organization and structure in JSON format.

Instructions

Get Excel file structure including sheet list and column headers in JSON format

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fileAbsolutePathYesThe absolute path of the Excel file
headerRowsNoNumber of header rows to read (default: 1)

Implementation Reference

  • Core handler function that loads the Excel workbook (using cache), extracts sheet names with indices, and for each sheet, parses column headers from the first 'headerRows' rows, structuring them into sheetField array.
    export async function analyzeExcelStructure(
        filePathWithName: string,
        headerRows: number = 1
    ): Promise<ExcelStructure> {
        try {
            const workbookResult: EnsureWorkbookResult = workbookCache.ensureWorkbook(filePathWithName);
            let workbook: XLSX.WorkBook;
    
            if (!workbookResult.success) {
                const readResult = await readAndCacheFile(filePathWithName);
                if (!readResult.success) {
                    throw new Error(`Failed to read file: ${readResult.data.errors}`);
                }
                workbook = workbookCache.get(filePathWithName)!;
            } else {
                workbook = workbookResult.data as XLSX.WorkBook;
            }
    
            const result: ExcelStructure = {
                sheetList: [],
                sheetField: []
            };
    
            result.sheetList = workbook.SheetNames.map((sheetName, index) => ({
                SheetNo: index + 1,  // 添加从1开始的序号
                SheetName: sheetName
            }));
            // 遍历所有工作表
            for (const sheetName of workbook.SheetNames) {
                const worksheet = workbook.Sheets[sheetName];
                
                // 获取原始数据
                const rawData = XLSX.utils.sheet_to_json(worksheet, {
                    raw: true,
                    defval: '',
                    header: 1
                });
    
                if (rawData.length === 0) {
                    continue;
                }
                // 获取每列的数据
                const columnCount = (rawData[0] as any[]).length;
                for (let colIndex = 0; colIndex < columnCount; colIndex++) {
                    const fieldInfo: any = {
                        SheetName: sheetName
                    };
    
                    // 根据 headerRows 获取指定数量的表头行
                    for (let i = 1; i <= headerRows; i++) {
                        const headerIndex = i - 1;
                        if (rawData.length > headerIndex) {
                            const rowData = rawData[headerIndex] as any[];
                            fieldInfo[`Field${i}`] = rowData[colIndex] || '';
                        } else {
                            fieldInfo[`Field${i}`] = '';
                        }
                    }
    
                    result.sheetField = result.sheetField || [];
                    result.sheetField.push(fieldInfo);
                }
            }
    
            return  result
            // {
            //     // 修改 sheetList 的映射,添加 SheetNo
            //     sheetList: workbook.SheetNames.map((sheetName, index) => ({ 
            //         SheetNo: index + 1,  // 添加从1开始的序号
            //         SheetName: sheetName 
            //     })),
            //     sheetField: result.sheetField || []
            // };
    
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            throw new Error(`Failed to get Excel structure: ${errorMessage}`);
        }
    }
  • Tool registration including description, Zod input schema, and wrapper handler that validates/normalizes input, checks file existence, delegates to core analyzeExcelStructure function, and formats JSON response.
    server.tool("analyzeExcelStructure", 'Get Excel file structure including sheet list and column headers in JSON format',
        {
            fileAbsolutePath: z.string().describe("The absolute path of the Excel file"),
            headerRows: z.number().default(1).describe("Number of header rows to read (default: 1)")
        },
        async (params: {
            fileAbsolutePath: string;
            headerRows: number;
        }) => {
            try {
                const normalizedPath = await normalizePath(params.fileAbsolutePath);
                if (normalizedPath === 'error') {
                    return {
                        content: [{
                            type: "text",
                            text: JSON.stringify({
                                error: `Invalid file path: ${params.fileAbsolutePath}`,
                                suggestion: "Please verify the file path and name"
                            })
                        }]
                    };
                }
    
                if (!(await fileExists(normalizedPath))) {
                    return {
                        content: [{
                            type: "text",
                            text: JSON.stringify({
                                error: `File not found: ${params.fileAbsolutePath}`,
                                suggestion: "Please verify the file path and name"
                            })
                        }]
                    };
                }
    
                const result = await analyzeExcelStructure(normalizedPath, params.headerRows);
    
                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify(result)
                    }]
                };
    
            } catch (error) {
                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify({
                            error: `Failed to get Excel structure: ${error}`,
                            suggestion: "Please verify all parameters"
                        })
                    }]
                };
            }
        }
    );
  • TypeScript interface defining the structure of the output returned by analyzeExcelStructure: sheetList with sheet number and name, and sheetField with per-column header fields.
    export interface ExcelStructure {
        sheetList: Array<{
            SheetNo: number;
            SheetName: string;
        }>;
        sheetField: Array<{
            SheetName: string;
            [key: `Field${number}`]: string;
        }>;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries full burden. It mentions reading header rows (via parameter context) but doesn't disclose critical behaviors: whether the tool requires file access permissions, handles large files, supports specific Excel formats, or has performance/rate limits. For a file analysis tool with zero annotation coverage, this leaves significant gaps.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that front-loads the core purpose. Every word earns its place: it specifies the action, target, content, and format without redundancy or fluff.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations and no output schema, the description adequately covers the basic purpose but lacks completeness for a file analysis tool. It doesn't explain what the JSON output contains beyond 'sheet list and column headers' (e.g., data types, sheet metadata), nor does it address error conditions or prerequisites like file existence.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema fully documents both parameters. The description adds no additional parameter semantics beyond what's in the schema (e.g., it doesn't explain how 'headerRows' affects the structure output). With high schema coverage, baseline 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb ('Get') and resource ('Excel file structure'), specifying what information is retrieved ('sheet list and column headers') and the output format ('JSON format'). However, it doesn't explicitly differentiate from sibling tools like 'readSheetNames' or 'readSheetData', which appear to have overlapping functionality.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. With siblings like 'readSheetNames' (likely just sheet names) and 'readSheetData' (likely sheet content), there's no indication of when this comprehensive structure analysis is preferred over more specific tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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/zhiwei5576/excel-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server