欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > JSON 转换为 Word 文档

JSON 转换为 Word 文档

2025/5/13 0:43:30 来源:https://blog.csdn.net/weixin_45737215/article/details/147746741  浏览:    关键词:JSON 转换为 Word 文档

以下是一个在 Spring Boot 中实现 JSON 转 Word 的示例:

  1. 首先,需要在项目中引入相关的依赖,如 jsonApache POI 等。在 pom.xml 文件中添加以下内容:

    <!-- JSON 相关依赖 -->
    <dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.13.3</version>
    </dependency><!-- Apache POI 相关依赖 -->
    <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. 创建一个 Java 类,用于将 JSON 转换为 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 {@PostMappingpublic ResponseEntity<byte[]> jsonToWord(@RequestBody Map<String, Object> json) throws IOException {// 创建一个 Word 文档XWPFDocument document = new XWPFDocument();// 创建一个新的段落XWPFParagraph paragraph = document.createParagraph();// 设置段落的文本内容为 JSON 的字符串形式paragraph.createRun().setText(new ObjectMapper().writeValueAsString(json));// 将 Word 文档转换为字节数组ByteArrayOutputStream outputStream = new ByteArrayOutputStream();document.write(outputStream);byte[] wordBytes = outputStream.toByteArray();// 设置响应头,指定内容类型为 Word 文,并档设置文件名return ResponseEntity.ok().header("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document").header("Content-Disposition", "attachment; filename=generated-word.docx").body(wordBytes);}
    }

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词