Skip to main content
Glama
zhiwei5576

Excel MCP Server

by zhiwei5576

exportExcelStructure

Extract sheet names and headers from an Excel file and save them to a new template file.

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 core handler function that exports Excel file structure. It calls analyzeExcelStructure to get the source file's sheet list and field headers, then calls writeSheetData to write them into a new Excel template 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}`);
        }
    }
  • The MCP tool registration for 'exportExcelStructure'. Defines the tool name, description, Zod schema (sourceFilePath, targetFilePath, headerRows), and the handler callback that validates paths, checks file existence, and calls the export handler.
        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"
                            })
                        }]
                    };
                }
            }
        );
    }
  • The writeSheetData helper function used by exportExcelStructure to create a new Excel workbook from SheetData. Creates a new workbook, converts each data entry to JSON-based sheets, and writes the file.
    export async function writeSheetData(
        filePathWithName: string,
        data: SheetData
    ): Promise<boolean> {
        try {
            // 创建新的工作簿
            const workbook = XLSX.utils.book_new();
    
            // 遍历数据对象的每个工作表
            for (const [sheetName, sheetData] of Object.entries(data)) {
                // 将数据转换为工作表
                const worksheet = XLSX.utils.json_to_sheet(sheetData);
    
                // 将工作表添加到工作簿
                XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
            }
    
            // 写入文件
            XLSX.writeFile(workbook, filePathWithName);
    
            return true;
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            throw new Error(`Failed to write Excel data: ${errorMessage}`);
        }
    }
  • Type definitions used by exportExcelStructure: ExcelStructure (input from analyzeExcelStructure) and SheetData (output format for writeSheetData).
    export interface SheetData {
        [sheetName: string]: any[];
    }
    
    export interface ExcelStructure {
        sheetList: Array<{
            SheetNo: number;
            SheetName: string;
        }>;
        sheetField: Array<{
            SheetName: string;
            [key: `Field${number}`]: string;
        }>;
    }
  • The analyzeExcelStructure helper function called by exportExcelStructure to extract sheet names and column headers from the source Excel file.
    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}`);
        }
    }
Behavior2/5

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

No annotations provided, so description must fully disclose behavior. Only states it exports to a new template file. Does not mention overwriting behavior, permission requirements, or what happens if target file exists. Limited behavioral context.

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?

Single sentence conveying purpose and output. No extraneous information. Efficient and focused.

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?

No output schema, but tool is simple. Description covers input and output briefly. Could clarify whether output includes only headers or all sheet content. Adequate for a straightforward export tool.

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 coverage is 100% with descriptions for all three parameters. The description adds 'sheets and headers' context but does not significantly enhance meaning beyond schema. Baseline of 3 is appropriate.

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

Purpose5/5

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

Clearly states the tool exports Excel file structure (sheets and headers) to a new template. Verb 'Export' and resource 'Excel file structure' are specific. Distinguishes from siblings like analyzeExcelStructure (analysis vs. export) and read/write tools.

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

Usage Guidelines3/5

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

Implied usage via description: use to export structure. No explicit when-to-use or when-not-to-use compared to siblings like analyzeExcelStructure. Lacks guidance on prerequisites or alternative use cases.

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