Skip to main content
Glama
zhiwei5576

Excel MCP Server

by zhiwei5576

exportExcelStructure

Extract sheet names and column headers from an Excel file to create a new template with the same structure, preserving data organization for reuse.

Instructions

Export Excel file structure (sheets and headers) to a new Excel template file

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sourceFilePathYesThe source Excel file path to analyze
targetFilePathYesThe target Excel file path to save structure
headerRowsNoNumber of header rows to analyze (default: 1)

Implementation Reference

  • The main handler function implementing the core logic of exporting Excel structure: analyzes source file, validates structure, converts to SheetData, and writes to target file.
    export async function exportExcelStructure(
        sourceFilePath: string,
        targetFilePath: string,
        headerRows: number = 1
    ): Promise<boolean> {
        try {
            // 1. 获取源文件的结构
            const structure = await analyzeExcelStructure(sourceFilePath, headerRows);
    
            // 校验结构数据
            if (!structure.sheetList || !Array.isArray(structure.sheetList) || structure.sheetList.length === 0) {
                throw new Error('Invalid Excel structure: sheetList is empty or invalid');
            }
    
            if (!structure.sheetField || !Array.isArray(structure.sheetField) || structure.sheetField.length === 0) {
                throw new Error('Invalid Excel structure: sheetField is empty or invalid');
            }
    
            // 2. 转换为 SheetData 格式
            const data: SheetData = {
                'sheetList': structure.sheetList,
                'sheetField': structure.sheetField
            };
    
            // 3. 使用 writeSheetData 写入文件
            return await writeSheetData(targetFilePath, data);
    
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            throw new Error(`Failed to export Excel structure: ${errorMessage}`);
        }
    }
  • MCP tool registration including description, Zod input schema, and wrapper handler that normalizes paths, validates files, and delegates to core exportExcelStructure function.
    server.tool("exportExcelStructure", 'Export Excel file structure (sheets and headers) to a new Excel template file',
        {
            sourceFilePath: z.string().describe("The source Excel file path to analyze"),
            targetFilePath: z.string().describe("The target Excel file path to save structure"),
            headerRows: z.number().default(1).describe("Number of header rows to analyze (default: 1)")
        },
        async (params: {
            sourceFilePath: string;
            targetFilePath: string;
            headerRows: number;
        }) => {
            try {
                // 验证源文件路径
                const normalizedSourcePath = await normalizePath(params.sourceFilePath);
                if (normalizedSourcePath === 'error') {
                    return {
                        content: [{
                            type: "text",
                            text: JSON.stringify({
                                error: `Invalid source file path: ${params.sourceFilePath}`,
                                suggestion: "Please verify the source file path"
                            })
                        }]
                    };
                }
    
                // 验证源文件是否存在
                if (!(await fileExists(normalizedSourcePath))) {
                    return {
                        content: [{
                            type: "text",
                            text: JSON.stringify({
                                error: `Source file not found: ${params.sourceFilePath}`,
                                suggestion: "Please verify the source file exists"
                            })
                        }]
                    };
                }
    
                // 验证目标文件路径
                const normalizedTargetPath = await normalizePath(params.targetFilePath);
                if (normalizedTargetPath === 'error') {
                    return {
                        content: [{
                            type: "text",
                            text: JSON.stringify({
                                error: `Invalid target file path: ${params.targetFilePath}`,
                                suggestion: "Please verify the target file path"
                            })
                        }]
                    };
                }
    
                // 验证目标文件是否已存在
                if (await fileExists(normalizedTargetPath)) {
                    return {
                        content: [{
                            type: "text",
                            text: JSON.stringify({
                                error: `Target file already exists: ${params.targetFilePath}`,
                                suggestion: "Please specify a different target file path"
                            })
                        }]
                    };
                }
    
                // 导出结构
                await exportExcelStructure(normalizedSourcePath, normalizedTargetPath, params.headerRows);
    
                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify({
                            success: true,
                            message: `Excel structure exported successfully to: ${normalizedTargetPath}`
                        })
                    }]
                };
    
            } catch (error) {
                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify({
                            error: `Failed to export Excel structure: ${error}`,
                            suggestion: "Please verify all parameters and try again"
                        })
                    }]
                };
            }
        }
    );
  • Zod schema defining input parameters for the tool.
    {
        sourceFilePath: z.string().describe("The source Excel file path to analyze"),
        targetFilePath: z.string().describe("The target Excel file path to save structure"),
        headerRows: z.number().default(1).describe("Number of header rows to analyze (default: 1)")
    },
  • TypeScript interface defining the ExcelStructure used for the exported data structure.
    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 the full burden of behavioral disclosure. It states the tool exports structure to a new file, implying it's a read-and-write operation, but doesn't cover critical aspects like whether it overwrites existing target files, requires specific permissions, handles errors, or has performance considerations. This leaves significant gaps for a tool with file I/O operations.

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

Conciseness4/5

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

The description is a single, efficient sentence that front-loads the core action ('Export Excel file structure') and specifies the output ('to a new Excel template file'). It avoids redundancy and waste, though it could be slightly more structured by separating purpose from context.

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

Completeness2/5

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

Given the complexity of file operations and the absence of annotations and output schema, the description is incomplete. It doesn't explain what the exported template contains (e.g., sheet names, header rows, formatting), how errors are handled, or the implications of the 'headerRows' parameter. For a tool with three parameters and no structured safety hints, more detail is needed to ensure proper usage.

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?

The input schema has 100% description coverage, with clear parameter details in the schema itself. The description adds no additional meaning beyond what the schema provides, such as explaining how 'headerRows' affects the analysis or the format of the output template. Since schema coverage is high, the baseline score of 3 is appropriate, as the description doesn't compensate but also doesn't detract.

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 'Export' and the resource 'Excel file structure (sheets and headers)', specifying it creates a 'new Excel template file'. It distinguishes from siblings like 'analyzeExcelStructure' (which likely analyzes without exporting) and 'readSheetNames' (which reads but doesn't export). However, it doesn't explicitly differentiate from all siblings, such as 'writeSheetData' (which writes data rather than structure).

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 like 'analyzeExcelStructure' or 'readSheetNames'. It lacks context on prerequisites, such as whether the source file must exist or be accessible, and doesn't mention exclusions or specific use cases beyond the basic action.

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