SpringBoot中實(shí)現(xiàn)JSON轉(zhuǎn)Word格式的示例詳解
以下是一個(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 類(lèi),用于將 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)容類(lè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)包含了,無(wú)需再單獨(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: 如果路徑無(wú)效,返回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)文章
解決axios發(fā)送post請(qǐng)求,springMVC接收不到數(shù)據(jù)問(wèn)題的處理
文章主要討論了Vue組件無(wú)法正確接收和處理Axios請(qǐng)求的問(wèn)題,并詳細(xì)描述了SpringMVC中使用@PathVariable、@RequestBody、@RequestParam的不同場(chǎng)景及其對(duì)應(yīng)的前端Axios寫(xiě)法2026-05-05
Springboot動(dòng)態(tài)配置AOP切點(diǎn)詳解
這篇文章主要介紹了Springboot動(dòng)態(tài)配置AOP切點(diǎn)詳解,Springboot 可以定義注解切點(diǎn)去攔截注解修飾的類(lèi)方法以及execution(xxxx)切點(diǎn)去攔截具體的類(lèi)方法,默認(rèn)情況下我們都會(huì)使用注解@PointCut去定義切點(diǎn),然后定義切面攔截切點(diǎn),需要的朋友可以參考下2023-09-09
Java數(shù)組隊(duì)列概念與用法實(shí)例分析
這篇文章主要介紹了Java數(shù)組隊(duì)列概念與用法,結(jié)合實(shí)例形式分析了Java數(shù)組隊(duì)列相關(guān)概念、原理、用法及操作注意事項(xiàng),需要的朋友可以參考下2020-03-03
詳解Maven 搭建spring boot多模塊項(xiàng)目(附源碼)
這篇文章主要介紹了詳解Maven 搭建spring boot多模塊項(xiàng)目(附源碼),具有一定的參考價(jià)值,有興趣的可以了解一下2017-09-09
springcloud項(xiàng)目快速開(kāi)始起始模板的實(shí)現(xiàn)
本文主要介紹了springcloud項(xiàng)目快速開(kāi)始起始模板思路的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12

