Skip to main content
Glama
ShcRes

JXLS Excel Template Generator

by ShcRes

generateJxlsTemplate

Generate Excel templates conforming to JXLS specifications for structured data processing. Define data structures and formats to create reusable templates for JSON or array data.

Instructions

根据输入参数生成符合JXLS规范的Excel模板文件

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
templateNameYes模板文件名称
dataStructYes数据结构定义
dataFormatYes数据格式类型
sampleDataNo示例数据(可选)
outputPathNo导出文件路径(可选)

Implementation Reference

  • Core handler function that implements the generateJxlsTemplate tool logic: validates request, generates Excel template based on json/array format, applies JXLS annotations, and returns response.
    def generate_template(self, request: GenerateTemplateRequest) -> GenerateTemplateResponse:
        """主要模板生成方法"""
        try:
            # 参数验证
            self._validate_request(request)
    
            # 生成文件路径
            file_path = self._generate_file_path(request.templateName, request.outputPath)
    
            # 根据数据格式生成模板
            if request.dataFormat == "json":
                area_annotation, each_annotation = self._create_json_template(request, file_path)
            else:  # array
                area_annotation, each_annotation = self._create_array_template(request, file_path)
    
            # 计算数据结构信息
            column_count = len(request.dataStruct.dataFields)
            last_cell = self.jxls_helper.calculate_last_cell(column_count, 2)
    
            # 构建响应
            jxls_annotations = JxlsAnnotations(
                area=area_annotation,
                each=each_annotation
            )
    
            data_struct_info = DataStructInfo(
                collectName=request.dataStruct.collectName,
                itemVariable=request.dataStruct.itemVariable,
                columnCount=column_count,
                lastCell=last_cell
            )
    
            return GenerateTemplateResponse.success_response(
                template_path=file_path,
                message="JXLS模板生成成功",
                jxls_annotations=jxls_annotations,
                data_struct=data_struct_info
            )
    
        except ValueError as e:
            return GenerateTemplateResponse.error_response(
                error="参数验证失败",
                details=str(e)
            )
        except Exception as e:
            return GenerateTemplateResponse.error_response(
                error="模板生成失败",
                details=str(e)
            )
  • MCP server handler for generateJxlsTemplate tool call: parses arguments, calls TemplateGenerator, formats response as TextContent.
    async def _handle_generate_template(self, arguments: Dict[str, Any]) -> List[TextContent]:
        """处理generateJxlsTemplate工具调用"""
        try:
            # 验证和解析请求
            request = GenerateTemplateRequest(**arguments)
            logger.info(f"生成模板请求: {request.templateName}, 格式: {request.dataFormat}")
    
            # 生成模板
            response = self.template_generator.generate_template(request)
    
            # 记录结果
            if response.success:
                logger.info(f"模板生成成功: {response.templatePath}")
            else:
                logger.error(f"模板生成失败: {response.error} - {response.details}")
    
            # 返回响应
            return [TextContent(
                type="text",
                text=response.model_dump_json(indent=2)
            )]
    
        except ValidationError as e:
            logger.error(f"请求参数验证失败: {e}")
            error_response = {
                "success": False,
                "message": "请求参数验证失败",
                "error": "参数验证失败",
                "details": str(e)
            }
            return [TextContent(
                type="text",
                text=str(error_response)
            )]
    
        except Exception as e:
            logger.error(f"处理请求时发生未知错误: {e}")
            error_response = {
                "success": False,
                "message": "处理请求时发生未知错误",
                "error": "内部服务器错误",
                "details": str(e)
            }
            return [TextContent(
                type="text",
                text=str(error_response)
            )]
  • Pydantic schema/model for GenerateTemplateRequest input validation.
    class GenerateTemplateRequest(BaseModel):
        """生成模板请求模型"""
    
        templateName: str = Field(
            ...,
            min_length=1,
            max_length=100,
            description="模板文件名称"
        )
        dataStruct: DataStruct = Field(..., description="数据结构定义")
        dataFormat: Literal["json", "array"] = Field(..., description="数据格式类型")
        sampleData: Optional[List[Any]] = Field(None, description="示例数据(用于验证)")
        outputPath: Optional[str] = Field(None, description="导出文件路径")
    
        @model_validator(mode='after')
        def validate_data_format_consistency(self) -> 'GenerateTemplateRequest':
            """验证数据格式与dataStruct的一致性
            
            对于需要数据绑定的字段:
            - JSON格式需要提供field属性
            - 数组格式需要提供index属性
            
            允许field和index都为空,表示该列不需要数据绑定
            """
            if self.dataFormat == "json":
                # JSON格式时,如果提供了index但没有field,则报错
                for field in self.dataStruct.dataFields:
                    if field.index is not None and not field.field:
                        raise ValueError(
                            f"JSON格式时字段'{field.name}'不应提供index属性,"
                            f"请使用field属性或留空表示不绑定数据"
                        )
            elif self.dataFormat == "array":
                # 数组格式时,如果提供了field但没有index,则报错
                for field in self.dataStruct.dataFields:
                    if field.field and field.index is None:
                        raise ValueError(
                            f"数组格式时字段'{field.name}'不应提供field属性,"
                            f"请使用index属性或留空表示不绑定数据"
                        )
            return self
  • Tool registration in MCP server list_tools, including inputSchema.
    Tool(
        name="generateJxlsTemplate",
        description="根据输入参数生成符合JXLS规范的Excel模板文件",
        inputSchema={
            "type": "object",
            "properties": {
                "templateName": {
                    "type": "string",
                    "description": "模板文件名称",
                    "minLength": 1,
                    "maxLength": 100
                },
                "dataStruct": {
                    "type": "object",
                    "description": "数据结构定义",
                    "properties": {
                        "collectName": {
                            "type": "string",
                            "description": "集合变量名称",
                            "minLength": 1
                        },
                        "itemVariable": {
                            "type": "string",
                            "description": "循环项变量名",
                            "minLength": 1
                        },
                        "dataFields": {
                            "type": "array",
                            "description": "字段定义数组",
                            "minItems": 1,
                            "items": {
                                "type": "object",
                                "properties": {
                                    "name": {
                                        "type": "string",
                                        "description": "列标题显示名称"
                                    },
                                    "field": {
                                        "type": "string",
                                        "description": "JSON格式字段名"
                                    },
                                    "index": {
                                        "type": "integer",
                                        "description": "数组格式索引位置",
                                        "minimum": 0
                                    }
                                },
                                "required": ["name"]
                            }
                        }
                    },
                    "required": ["collectName", "itemVariable", "dataFields"]
                },
                "dataFormat": {
                    "type": "string",
                    "enum": ["json", "array"],
                    "description": "数据格式类型"
                },
                "sampleData": {
                    "type": "array",
                    "description": "示例数据(可选)",
                    "items": {}
                },
                "outputPath": {
                    "type": "string",
                    "description": "导出文件路径(可选)"
                }
            },
            "required": ["templateName", "dataStruct", "dataFormat"]
        }
    )
  • Pydantic model for output response structure.
    class GenerateTemplateResponse(BaseModel):
        """生成模板响应模型"""
    
        success: bool = Field(..., description="操作是否成功")
        templatePath: Optional[str] = Field(None, description="生成的模板文件路径")
        message: str = Field(..., description="响应消息")
        jxlsAnnotations: Optional[JxlsAnnotations] = Field(None, description="JXLS批注信息")
        dataStruct: Optional[DataStructInfo] = Field(None, description="数据结构信息")
        error: Optional[str] = Field(None, description="错误类型")
        details: Optional[str] = Field(None, description="错误详细信息")
    
        @classmethod
        def success_response(
                cls,
                template_path: str,
                message: str,
                jxls_annotations: JxlsAnnotations,
                data_struct: DataStructInfo
        ) -> 'GenerateTemplateResponse':
            """创建成功响应"""
            return cls(
                success=True,
                templatePath=template_path,
                message=message,
                jxlsAnnotations=jxls_annotations,
                dataStruct=data_struct
            )
    
        @classmethod
        def error_response(
                cls,
                error: str,
                details: str,
                message: Optional[str] = None
        ) -> 'GenerateTemplateResponse':
            """创建错误响应"""
            return cls(
                success=False,
                message=message or f"操作失败: {error}",
                error=error,
                details=details
            )
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 but only states the basic function. It lacks details on permissions, side effects, rate limits, output format, or error handling, which are critical for a tool that generates files.

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 directly states the tool's function without unnecessary words. It is appropriately sized and front-loaded, making it easy to understand quickly.

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 (5 parameters, nested objects, no output schema, and no annotations), the description is inadequate. It fails to explain the generated file's format, usage examples, or behavioral traits, leaving significant gaps for an AI agent to invoke the tool correctly.

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 description does not add meaning beyond the input schema, which has 100% coverage with detailed parameter descriptions. Since the schema fully documents the parameters, 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 action ('生成' - generate) and the resource ('符合JXLS规范的Excel模板文件' - JXLS-compliant Excel template file), making the purpose specific and understandable. However, with no sibling tools mentioned, it cannot distinguish from alternatives, 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, prerequisites, or contextual constraints. It merely states what the tool does without indicating appropriate scenarios or limitations.

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/ShcRes/jxls-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server