python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python Word与JSON互转

Python使用FastMCP实现Word文档与JSON数据互转

作者:东方佑

这篇文章主要介绍了基于FastMCP框架实现的文档处理服务,可实现 Word 文档(.docx)与 JSON 数据格式的双向转换,通过此服务,开发者可以轻松实现文档内容提取、结构化数据填充、样式模板复用等功能,适用于自动化报告生成、数据导入导出等场景,需要的朋友可以参考下

一、项目背景

本文分享一个基于 FastMCP 框架实现的文档处理服务,可实现 Word 文档(.docx)与 JSON 数据格式的双向转换。通过此服务,开发者可以轻松实现文档内容提取、结构化数据填充、样式模板复用等功能,适用于自动化报告生成、数据导入导出等场景。

二、核心代码解析

1. 服务端实现(my_server.py)

import json
from fastmcp import FastMCP
from wan_neng_copy_word import clone_document as word_to_dict
from wan_neng_copy_word_pro import clone_document
from wan_neng_copy_word import clone_document as get_para_style
from gen_all_styles import gen_all_styles

mcp = FastMCP(name="MyServer")

# 基础问候工具
@mcp.tool
def greet(name: str) -> str:
    """Greet a user by name."""
    return f"Hello, {name}!"

# Word 转 JSON 工具
@mcp.tool
def word_to_json(word_path: str) -> str:
    """Convert a word document to json."""
    body_s, body_p = word_to_dict(word_path)
    return json.dumps(body_p)

# JSON 转 Word 工具
@mcp.tool
def json_to_word(word_path: str, json_data: str) -> str:
    """Convert a json to word document."""
    try:
        body_ws, _ = get_para_style('demo_template.docx')
    except:
        gen_all_styles()
        body_ws, _ = get_para_style('demo_template.docx')

    body_s, _ = get_para_style(word_path)
    clone_document(body_s, json.loads(json_data), body_ws, 'cloned_example.docx')
    return 'cloned_example.docx'

# 启动 MCP 服务
if __name__ == "__main__":
    mcp.run(transport="streamable-http", host="127.0.0.1", port=9000)

关键组件说明:

2. 客户端测试代码

import asyncio
from fastmcp import Client

# MCP 服务配置
config = {
    "mcpServers": {
        "document-service": {
            "url": "http://127.0.0.1:9000/mcp",
            "transport": "streamable-http"
        }
    }
}

# 创建客户端实例
client = Client(config)

async def main():
    async with client:
        # 读取 JSON 数据
        with open("1.json", "r", encoding="utf-8") as f:
            body_p = f.read()
        
        # 调用 JSON 转 Word 工具
        result = await client.call_tool(
            "json_to_word", 
            {"word_path": "1.docx", "json_data": body_p}
        )
        print(f"生成文档路径: {result}")

if __name__ == "__main__":
    asyncio.run(main())

三、运行环境要求

pip install fastmcp python-docx

四、功能演示流程

启动服务:

python my_server.py

执行客户端测试:

python client_test.py

五、应用场景

六、注意事项

# 可扩展的异常处理示例
try:
    # 文件操作代码
except FileNotFoundError as e:
    return {"error": f"Missing file: {str(e)}"}
except json.JSONDecodeError:
    return {"error": "Invalid JSON input"}

七、扩展建议

添加文件校验模块:

def validate_word_file(path):
    if not os.path.exists(path):
        raise ValueError("Template file not found")
    if not path.endswith('.docx'):
        raise ValueError("Invalid file format")

支持更多格式转换:

API 接口增强:

该实现展示了如何通过 MCP 协议构建文档处理服务,开发者可根据实际需求扩展更多文档操作功能。完整项目代码需注意分离服务端/客户端模块,并完善错误处理机制。

以上就是Python使用FastMCP实现Word文档与JSON数据互转的详细内容,更多关于Python Word与JSON互转的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文