Skip to main content
Glama
zhiwei5576

Excel MCP Server

by zhiwei5576

writeDataBySheetName

Write data to a specified sheet in an Excel file, overwriting any existing content in that sheet.

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 data to a specific sheet in an Excel file. If the file exists, it reads the existing workbook; if not, it creates a new one. If the sheet already exists, it deletes and replaces it. Converts data using XLSX.utils.json_to_sheet, appends it, writes to file, and updates the 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}`);
        }
    }
  • Registration of the 'writeDataBySheetName' tool with MCP server. Defines the input schema (fileAbsolutePath, sheetName, data array of records), validates inputs, calls the handler, and returns a success/error response.
    export const writeTools = (server: any) => {
        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"
                            })
                        }]
                    };
                }
            }
        );
  • The SheetData interface defines the type used by writeSheetData (a related tool). The writeDataBySheetName handler uses raw `any[]` data directly, so this is the closest schema type definition.
    export interface SheetData {
        [sheetName: string]: any[];
    }
Behavior2/5

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

Discloses an important behavioral trait (overwrites if sheet exists), but lacks other details like return value, error handling, or authorization requirements. Without annotations, the description carries the full burden.

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

Conciseness3/5

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

Single sentence with key information, but it is too minimal and does not justify its brevity with additional necessary 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?

No output schema and no details about success feedback or error cases. For a write operation, this is insufficiently complete.

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?

All parameters are covered by schema descriptions (100% coverage), so the description adds minimal additional meaning. The note about overwriting is about tool behavior, not parameters.

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 verb (Write data) and resource (specific sheet in Excel file), but does not differentiate from sibling tool 'writeSheetData', which likely performs a similar function.

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?

No guidance on when to use this tool vs alternatives like 'writeSheetData', nor any prerequisites or conditions of use.

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