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 類,用于將 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)包含了,無(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)文章
ByteArrayOutputStream與InputStream互相轉(zhuǎn)換方式
這篇文章主要介紹了ByteArrayOutputStream與InputStream互相轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
Java 實(shí)戰(zhàn)項(xiàng)目之誠(chéng)途旅游系統(tǒng)的實(shí)現(xiàn)流程
讀萬(wàn)卷書(shū)不如行萬(wàn)里路,只學(xué)書(shū)上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SpringBoot+Vue+maven+Mysql實(shí)現(xiàn)一個(gè)精美的物流管理系統(tǒng),大家可以在過(guò)程中查缺補(bǔ)漏,提升水平2021-11-11
從繁瑣到簡(jiǎn)潔的Jenkins?Pipeline腳本優(yōu)化實(shí)踐
這篇文章主要為大家介紹了從繁瑣到簡(jiǎn)潔的Jenkins?Pipeline腳本優(yōu)化實(shí)踐示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
關(guān)于Spring中的@Configuration中的proxyBeanMethods屬性
這篇文章主要介紹了關(guān)于Spring中的@Configuration中的proxyBeanMethods屬性,需要的朋友可以參考下2023-07-07
springboot實(shí)現(xiàn)郵箱發(fā)送(激活碼)功能的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用springboot實(shí)現(xiàn)郵箱發(fā)送(激活碼)功能,文中的示例代碼簡(jiǎn)潔易懂,有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-10-10
SpringBoot實(shí)現(xiàn)文件上傳并返回url鏈接的示例代碼
文件上傳,當(dāng)我們選擇了某一個(gè)圖片文件之后,這個(gè)文件就會(huì)上傳到服務(wù)器,從而完成文件上傳的操作,是指將本地圖片、視頻、音頻等文件上傳到服務(wù)器,供其他用戶瀏覽或下載的過(guò)程,本文給大家介紹了SpringBoot實(shí)現(xiàn)文件上傳并返回url鏈接,需要的朋友可以參考下2024-11-11
SpringBoot小程序推送信息的項(xiàng)目實(shí)踐
本文主要介紹了SpringBoot小程序推送信息的項(xiàng)目實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
關(guān)于Java中如何實(shí)現(xiàn)文件的讀寫操作
在Java中,可以使用File和FileInputStream、FileOutputStream、BufferedReader、PrintWriter等類來(lái)進(jìn)行文件讀寫操作,需要的朋友可以參考下2023-05-05

