Skip to main content
Glama
zhiwei5576

Excel MCP Server

by zhiwei5576

writeDataBySheetName

Write data to a specific sheet in an Excel file, overwriting existing content if the sheet already exists.

Instructions

Write data to a specific sheet in the Excel file (overwrites if sheet exists)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fileAbsolutePathYesThe absolute path of the Excel file
sheetNameYesThe name of the sheet to write
dataYesArray of objects to write to the sheet

Implementation Reference

  • Core handler function that writes the provided data array to a specific sheet in the Excel file. Loads existing workbook from cache if file exists, overwrites the sheet if present, creates new workbook if not. Uses XLSX library for manipulation and updates cache.
    export async function writeDataBySheetName(
        filePathWithName: string,
        sheetName: string,
        data: any[]
    ): Promise<boolean> {
        try {
            let workbook: XLSX.WorkBook;
    
    
            // 检查文件是否存在,注:filePathWithName ,已经经过了normalizePath
            if (await fileExists(filePathWithName)) {
                // 如果文件存在,读取现有工作簿
                const workbookResult = workbookCache.ensureWorkbook(filePathWithName);
                if (!workbookResult.success) {
                    const readResult = await readAndCacheFile(filePathWithName);
                    if (!readResult.success) {
                        throw new Error(`Failed to read existing file: ${readResult.data.errors}`);
                    }
                    workbook = workbookCache.get(filePathWithName)!;
                } else {
                    workbook = workbookResult.data as XLSX.WorkBook;
                }
            } else {
                // 如果文件不存在,创建新的工作簿
                workbook = XLSX.utils.book_new();
            }
    
            // 将数据转换为工作表
            const worksheet = XLSX.utils.json_to_sheet(data);
    
            // 检查工作表是否已存在
            if (workbook.SheetNames.includes(sheetName)) {
                // 如果存在,删除旧的工作表
                const index = workbook.SheetNames.indexOf(sheetName);
                workbook.SheetNames.splice(index, 1);
                delete workbook.Sheets[sheetName];
            }
    
            // 添加新的工作表
            XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
    
            // 写入文件
            XLSX.writeFile(workbook, filePathWithName);
    
            // 更新缓存
            workbookCache.set(filePathWithName, workbook);
    
            return true;
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            throw new Error(`Failed to write sheet data: ${errorMessage}`);
        }
    }
  • Registers the 'writeDataBySheetName' tool on the MCP server. Includes Zod schema for input validation (fileAbsolutePath, sheetName, data), path normalization, input checks, calls the core handler, and formats success/error responses.
    server.tool("writeDataBySheetName", 'Write data to a specific sheet in the Excel file (overwrites if sheet exists)',
        {
            fileAbsolutePath: z.string().describe("The absolute path of the Excel file"),
            sheetName: z.string().describe("The name of the sheet to write"),
            data: z.array(
                z.record(
                    z.string(),
                    z.any()
                )
            ).describe("Array of objects to write to the sheet")
        },
        async (params: {
            fileAbsolutePath: string;
            sheetName: string;
            data: 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 (!Array.isArray(params.data) || params.data.length === 0) {
                    return {
                        content: [{
                            type: "text",
                            text: JSON.stringify({
                                error: "Empty data array provided",
                                suggestion: "Please provide non-empty array of data"
                            })
                        }]
                    };
                }
    
                // 校验工作表名称
                if (!params.sheetName) {
                    return {
                        content: [{
                            type: "text",
                            text: JSON.stringify({
                                error: "Invalid sheet name",
                                suggestion: "Please provide a valid sheet name"
                            })
                        }]
                    };
                }
    
                await writeDataBySheetName(normalizedPath, params.sheetName, params.data);
                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify({
                            success: true,
                            message: `Data written successfully to sheet '${params.sheetName}' in file: ${normalizedPath}`
                        })
                    }]
                };
    
            } catch (error) {
                return {
                    content: [{
                        type: "text",
                        text: JSON.stringify({
                            error: `Failed to write sheet data: ${error}`,
                            suggestion: "Please verify all parameters and try again"
                        })
                    }]
                };
            }
        }
    );
  • Zod schema defining the input parameters for the tool: fileAbsolutePath (string), sheetName (string), data (array of records).
        fileAbsolutePath: z.string().describe("The absolute path of the Excel file"),
        sheetName: z.string().describe("The name of the sheet to write"),
        data: z.array(
            z.record(
                z.string(),
                z.any()
            )
        ).describe("Array of objects to write to the sheet")
    },
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states that the tool 'overwrites if sheet exists,' which is a useful behavioral trait (destructive operation). However, it lacks other critical details such as required permissions, file format constraints, error handling, or whether it creates a new sheet if it doesn't exist. For a mutation tool with zero annotation coverage, this is insufficient.

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 action and includes a key behavioral note ('overwrites if sheet exists'). There is no wasted text, and every word contributes to understanding the tool's function, making it appropriately concise and well-structured.

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 the tool's complexity (a write operation with 3 parameters), no annotations, and no output schema, the description is moderately complete. It covers the basic purpose and a key behavioral trait but lacks details on permissions, error cases, or return values. For a mutation tool without structured support, it should do more to be fully helpful, but it meets a minimum viable level.

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, providing clear documentation for all three parameters. The description adds no additional semantic details about the parameters beyond what the schema already states (e.g., it doesn't explain data format expectations or sheet naming rules). According to the rules, with high schema coverage (>80%), the baseline is 3 even without param info in the description.

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 action ('Write data') and target resource ('to a specific sheet in the Excel file'), making the purpose immediately understandable. It distinguishes itself from siblings like 'readDataBySheetName' by specifying a write operation. However, it doesn't explicitly differentiate from 'writeSheetData' (a sibling tool), which might perform a similar function, preventing a perfect score.

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 'writeSheetData' or other siblings. It mentions that it 'overwrites if sheet exists,' which hints at behavior but doesn't clarify usage contexts, prerequisites, or exclusions. Without explicit when/when-not instructions or named alternatives, this falls short of higher scores.

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