Here is an example of implementing JSON to Word in Spring Boot:
1. First of all, relevant dependencies need to be introduced into the project, such asjson
andApache POI
wait. existAdd the following content to the file:
<!-- JSON Related dependencies --> <dependency> <groupId></groupId> <artifactId>jackson-databind</artifactId> <version>2.13.3</version> </dependency> <!-- Apache POI Related dependencies --> <dependency> <groupId></groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.3</version> </dependency> <dependency> <groupId></groupId> <artifactId>poi</artifactId> <version>5.2.3</version> </dependency>
2. Create a Java class to convert JSON to Word document. The following is the sample code:
import ; import ; import ; import ; import .*; import ; import ; ; @RestController @RequestMapping("/json-to-word") public class JsonToWordController { @PostMapping public ResponseEntity<byte[]> jsonToWord(@RequestBody Map<String, Object> json) throws IOException { // Create a Word document XWPFDocument document = new XWPFDocument(); // Create a new paragraph XWPFParagraph paragraph = (); // Set the text content of the paragraph to JSON string form ().setText(new ObjectMapper().writeValueAsString(json)); // Convert Word documents to byte array ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); (outputStream); byte[] wordBytes = (); // Set the response header, specify the content type as Word text, and set the file name in conjunction with the file return () .header("Content-Type", "application/") .header("Content-Disposition", "attachment; filename=") .body(wordBytes); } }
3. Knowledge extension
Springboot comes with json conversion
There are too many deserialization vulnerabilities in Alibaba fastjson. They often change the version and change it to the jackson that comes with springboot.
Maven alone
<dependency> <groupId></groupId> <artifactId>jackson-databind</artifactId> <version>2.11.1</version> </dependency>
The web project spring-boot-starter-web has been included, no need to quote separately
<dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
package test; import ; import ; import ; import ; import ; public class Test { public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> person = new HashMap<>(); ("name", "zhangsan"); ("age", 18); List<Map<String, Object>> personList = new ArrayList<>(); (person); //Object to JSON string String jsonmap = (person); (jsonmap);//{"name":"zhangsan","age":18} String jsonlist = (personList); (jsonlist);//[{"name":"zhangsan","age":18}] //Json string to object Map<String, Object> map = (jsonmap, ); List<Map<String, Object>> list = (jsonlist, ); (); } }
Fastapi interface implements json format to word
After running fastapi api, the browser enters http://127.0.0.1:8000/redoc download interface json
openapi_data
For the contents in the json file, you need to put the jsontrue
Modify toTrue
, a word document will be generated in the same level directory. The code is as follows:
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": "Download the trained model fileAPIEndpoint。\n\nArgs:\n request (DownloadRequest): Request body containing the path to the model file。 file_path: str # File path, must be provided\n\nReturns:\n FileResponse: Returns the model file stream. \n\nRaises:\n HTTPException: If the file does not exist, a 404 error is returned. \n HTTPException: If the path is invalid, return 400 error. ", "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 (): doc.add_heading(f"{()} {path}", level=2) doc.add_paragraph(f"Summary: {('summary', 'No summary')}") doc.add_paragraph(f"Description: {('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: {('description', 'No description')}") doc.add_paragraph(f"Required: {', '.join(('required', []))}") doc.add_paragraph(f"Properties:") for prop, prop_details in ('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: {('description', 'No description')}") # Save the document to a BytesIO buffer buffer = BytesIO() (buffer) (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: (())
This is the end of this article about the detailed explanation of the examples of implementing JSON to Word format in SpringBoot. For more related SpringBoot JSON to Word content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!