欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot中實(shí)現(xiàn)JSON轉(zhuǎn)Word格式的示例詳解

 更新時(shí)間:2025年05月07日 11:33:55   作者:搬磚牛馬人  
這篇文章主要為大家詳細(xì)介紹了如何使用SpringBoot實(shí)現(xiàn)JSON轉(zhuǎn)Word格式,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

以下是一個(gè)在 Spring Boot 中實(shí)現(xiàn) JSON 轉(zhuǎn) Word 的示例:

1.首先,需要在項(xiàng)目中引入相關(guān)的依賴,如 json 和 Apache POI 等。在 pom.xml 文件中添加以下內(nèi)容:

<!-- JSON 相關(guān)依賴 -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.3</version>
</dependency>
 
<!-- Apache POI 相關(guān)依賴 -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version>
</dependency>
 
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.3</version>
</dependency>

2.創(chuàng)建一個(gè) Java 類,用于將 JSON 轉(zhuǎn)換為 Word 文檔,以下是示例代碼:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
 
import java.io.ByteArrayOutputStream;
import java.io.IOExceptionimport;
 java.util.Map;
 
@RestController
@RequestMapping("/json-to-word")
public class JsonToWordController {
 
    @PostMapping
    public ResponseEntity<byte[]> jsonToWord(@RequestBody Map<String, Object> json) throws IOException {
        // 創(chuàng)建一個(gè) Word 文檔
        XWPFDocument document = new XWPFDocument();
 
        // 創(chuàng)建一個(gè)新的段落
        XWPFParagraph paragraph = document.createParagraph();
        // 設(shè)置段落的文本內(nèi)容為 JSON 的字符串形式
        paragraph.createRun().setText(new ObjectMapper().writeValueAsString(json));
 
        // 將 Word 文檔轉(zhuǎn)換為字節(jié)數(shù)組
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        document.write(outputStream);
        byte[] wordBytes = outputStream.toByteArray();
 
        // 設(shè)置響應(yīng)頭,指定內(nèi)容類型為 Word 文,并檔設(shè)置文件名
        return ResponseEntity.ok()
                .header("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                .header("Content-Disposition", "attachment; filename=generated-word.docx")
                .body(wordBytes);
    }
}

3.知識(shí)延展

springboot自帶json轉(zhuǎn)換

阿里fastjson反序列化漏洞,實(shí)在太多了,經(jīng)常換版本,改成springboot自帶的jackson。

Maven單獨(dú)使用

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.1</version>
        </dependency>

web項(xiàng)目spring-boot-starter-web已經(jīng)包含了,無需再單獨(dú)引用

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
package test;
 
import com.fasterxml.jackson.databind.ObjectMapper;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class Test {
 
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
 
        Map<String, Object> person = new HashMap<>();
        person.put("name", "zhangsan");
        person.put("age", 18);
 
        List<Map<String, Object>> personList = new ArrayList<>();
        personList.add(person);
 
        //對(duì)象轉(zhuǎn)json字符串
        String jsonmap = mapper.writeValueAsString(person);
        System.out.println(jsonmap);//{"name":"zhangsan","age":18}
        String jsonlist = mapper.writeValueAsString(personList);
        System.out.println(jsonlist);//[{"name":"zhangsan","age":18}]
 
        //json字符串轉(zhuǎn)對(duì)象
        Map<String, Object> map = mapper.readValue(jsonmap, Map.class);
        List<Map<String, Object>> list = mapper.readValue(jsonlist, List.class);
        System.out.println();
    }
}

fastapi 接口實(shí)現(xiàn)json格式轉(zhuǎn)word

fastapi api 運(yùn)行之后 瀏覽器進(jìn)入 http://127.0.0.1:8000/redoc 下載接口json

openapi_data 為json文件中的內(nèi)容,需要把json中的true 修改為True,會(huì)在同級(jí)目錄下生成一個(gè)word文檔。代碼如下:

from docx import Document
from io import BytesIO

openapi_data = {
    "openapi": "3.1.0",
    "info": {
        "title": "FastAPI",
        "version": "0.1.0"
    },
    "paths": {

        "/download-model": {
            "post": {
                "summary": "Download Model",
                "description": "下載訓(xùn)練好的模型文件的API端點(diǎn)。\n\nArgs:\n    request (DownloadRequest): 包含模型文件路徑的請(qǐng)求體。 file_path: str  # 文件路徑,必須提供\n\nReturns:\n    FileResponse: 返回模型文件流。\n\nRaises:\n    HTTPException: 如果文件不存在,返回404錯(cuò)誤。\n    HTTPException: 如果路徑無效,返回400錯(cuò)誤。",
                "operationId": "download_model_download_model_post",
                "requestBody": {
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/DownloadRequest"
                            }
                        }
                    },
                    "required": True
                },
                "responses": {
                    "200": {
                        "description": "Successful Response",
                        "content": {
                            "application/json": {
                                "schema": {}
                            }
                        }
                    },
                    "422": {
                        "description": "Validation Error",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/HTTPValidationError"
                                }
                            }
                        }
                    }
                }
            }
        }
    },
    "components": {

    }
}

doc = Document()
doc.add_heading('API Documentation', 0)

# Add API information
doc.add_heading('API Information', level=1)
doc.add_paragraph(f"Title: {openapi_data['info']['title']}")
doc.add_paragraph(f"Version: {openapi_data['info']['version']}")

# Add path information
doc.add_heading('API Endpoints', level=1)
for path, methods in openapi_data['paths'].items():
    for method, details in methods.items():
        doc.add_heading(f"{method.upper()} {path}", level=2)
        doc.add_paragraph(f"Summary: {details.get('summary', 'No summary')}")
        doc.add_paragraph(f"Description: {details.get('description', 'No description')}")
        if 'requestBody' in details:
            doc.add_heading('Request Body', level=3)
            for content_type, content in details['requestBody']['content'].items():
                doc.add_paragraph(f"Content-Type: {content_type}")
                schema_ref = content['schema'].get('$ref', None)
                if schema_ref:
                    schema_name = schema_ref.split('/')[-1]
                    schema = openapi_data['components']['schemas'][schema_name]
                    doc.add_paragraph(f"Schema: {schema_name}")
                    doc.add_paragraph(f"Description: {schema.get('description', 'No description')}")
                    doc.add_paragraph(f"Required: {', '.join(schema.get('required', []))}")
                    doc.add_paragraph(f"Properties:")
                    for prop, prop_details in schema.get('properties', {}).items():
                        doc.add_paragraph(f"- {prop} ({prop_details.get('type', 'unknown')}): {prop_details.get('title', '')}")

        if 'responses' in details:
            doc.add_heading('Responses', level=3)
            for status_code, response in details['responses'].items():
                doc.add_paragraph(f"Status Code: {status_code}")
                doc.add_paragraph(f"Description: {response.get('description', 'No description')}")

# Save the document to a BytesIO buffer
buffer = BytesIO()
doc.save(buffer)
buffer.seek(0)

# Save the file to disk (or you can return it as a download in a web app)
with open("api_documentation.docx", "wb") as f:
    f.write(buffer.read())

到此這篇關(guān)于SpringBoot中實(shí)現(xiàn)JSON轉(zhuǎn)Word格式的示例詳解的文章就介紹到這了,更多相關(guān)SpringBoot JSON轉(zhuǎn)Word內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論