Skip to main content
Glama
zhiwei5576

Excel MCP Server

by zhiwei5576

writeSheetData

Create a new Excel file by providing a file path and a data object with dynamic sheet names and column names.

Instructions

Create a new Excel file with provided data

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fileAbsolutePathYesThe absolute path for the new Excel file
dataYesData object with dynamic sheet names and column names

Implementation Reference

  • Core handler function that creates a new Excel workbook from provided SheetData, iterates over each sheet entry, converts JSON data to worksheet using XLSX.utils.json_to_sheet, appends sheets to workbook, and writes to file using XLSX.writeFile.
    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 definition for the data parameter accepted by writeSheetData – a record mapping sheet names to arrays of row data.
    export interface SheetData {
        [sheetName: string]: any[];
    }
  • Registration of the 'writeSheetData' tool on the MCP server using server.tool(), defining input schema with Zod (fileAbsolutePath string, data as a record of sheet names to arrays of row objects), validation logic, and invocation of the handler.
    server.tool("writeSheetData", 'Create a new Excel file with provided data',
        {
            fileAbsolutePath: z.string().describe("The absolute path for the new Excel file"),
            data: z.record(
                z.string(), // 表名(动态)
                z.array(    // 表数据数组
                    z.record( // 每行数据对象
                        z.string(), // 字段名(动态)
                        z.any()     // 字段值(任意类型)
                    )
                )
            ).describe("Data object with dynamic sheet names and column names")
        },
        async (params: {
            fileAbsolutePath: string;
            data: Record<string, Record<string, any>[]>;
        }) => {
            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 (Object.keys(params.data).length === 0) {
                    return {
                        content: [{
                            type: "text",
                            text: JSON.stringify({
                                error: "Empty data object provided",
                                suggestion: "Please provide at least one sheet with data"
                            })
                        }]
                    };
                }
    
                // 校验每个表的数据
                for (const [sheetName, sheetData] of Object.entries(params.data)) {
                    if (!Array.isArray(sheetData) || sheetData.length === 0) {
                        return {
                            content: [{
                                type: "text",
                                text: JSON.stringify({
                                    error: `Invalid data format in sheet "${sheetName}": Data must be a non-empty array`,
                                    suggestion: "Please check the data format of each sheet"
                                })
                            }]
                        };
                    }
                }
    
                if (await fileExists(normalizedPath)) {
                    return {
                        content: [{
                            type: "text",
                            text: JSON.stringify({
                                error: `File already exists: ${params.fileAbsolutePath}`,
                                suggestion: "Please specify a different file path"
                            })
                        }]
                    };
                }
    
                await writeSheetData(normalizedPath, params.data);
                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify({
                            success: true,
                            message: `Excel file created successfully: ${normalizedPath}`
                        })
                    }]
                };
    
            } catch (error) {
                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify({
                            error: `Failed to write Excel data: ${error}`,
                            suggestion: "Please verify the data format and file path"
                        })
                    }]
                };
            }
        }
    );
  • src/index.ts:24-25 (registration)
    Main entry point that calls writeTools(server) to register all write-related tools including writeSheetData on the MCP server.
    writeTools(server);
    cacheTools(server);   
Behavior2/5

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

No annotations provided, so description carries full burden. It mentions file creation but does not disclose behavior like overwriting existing files, file format, or error conditions. The complex data schema is not explained beyond schema descriptions.

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 sentence, making it very concise. However, it sacrifices completeness for brevity; while no wasted words, it omits critical details.

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 complex nested input schema and lack of output schema, the description is incomplete. It does not explain what the tool returns (e.g., file path or success message), how to handle errors, or how to structure the data parameter properly.

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

Parameters2/5

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

Schema description coverage is 100%, but the description adds no extra meaning beyond the schema's parameter descriptions. The data parameter's nested structure is not clarified; e.g., whether keys map to sheet names is left implicit.

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?

The description clearly states the action (create) and resource (new Excel file with provided data). It distinguishes from sibling tools like writeDataBySheetName, which modify existing files, making the purpose unambiguous.

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?

The description implies creation of a new file but does not explicitly state when to use this tool over alternatives (e.g., writeDataBySheetName). It lacks guidance on prerequisites, such as whether the file must not exist or what happens if it does.

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