Spring Boot + FreeMarker 实现动态Word文档导出

Spring Boot + FreeMarker 实现动态Word文档导出

在现代企业应用中,文档自动化生成是一项提升工作效率的重要功能。Spring Boot与FreeMarker的组合,为开发者提供了一个强大的平台,可以轻松实现动态Word文档的导出。本文将指导你如何使用Spring Boot与FreeMarker模板引擎,创建一个简单的应用,用于根据数据库数据动态生成Word文档并下载。

技术栈简介

  • Spring Boot:简化Spring应用初始搭建以及开发过程的框架,提供了快速开发、运行、部署的解决方案。
  • FreeMarker:一款用Java编写的模板引擎,特别适合生成HTML、XML、RTF、Java源代码等文本格式的输出,当然也包括Word文档。

准备工作

1. 创建Spring Boot项目

使用Spring Initializr创建一个新的Spring Boot项目,记得勾选Thymeleaf(虽然我们用FreeMarker,但Thymeleaf依赖也会带来Spring MVC的支持,便于后续配置)。

2. 添加FreeMarker依赖

pom.xml中加入FreeMarker的依赖。

xml 复制代码
<dependency> 
  <groupId>org.springframework.boot</groupId> 
  <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

3. 配置FreeMarker

application.properties中配置FreeMarker的路径。

yaml 复制代码
spring.freemarker.template-loader-path=classpath:/templates/

创建FreeMarker模板

src/main/resources/templates目录下,创建一个名为document.ftl的FreeMarker模板文件,内容如下:

html 复制代码
<!DOCTYPE html>
<html> <head> <#assign document = { "title": "动态Word文档", "content": [ {"header": "章节一", "text": "这里是章节一的内容..."}, {"header": "章节二", "text": "这里是章节二的内容..."} ] }> </head> <body> <h1>${document.title}</h1> <#list document.content as section> <h2>${section.header}</h2> <p>${section.text}</p> </#list> </body> </html>

编写Controller

创建一个Controller来处理请求,读取模板并填充数据,最后将Word文档返回给用户下载。

java 复制代码
java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import freemarker.template.Configuration; import freemarker.template.Template; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity;
import java.io.IOException; import java.util.HashMap; import java.util.Map;
@RestController public class DocumentController {
@Autowired
private Configuration freemarkerConfig;

@GetMapping("/export")
public ResponseEntity<byte[]> exportDocument() throws IOException {
    // 假设数据是从数据库获取的,这里为了简化直接构造示例数据
    Map<String, Object> dataModel = new HashMap<>();
    dataModel.put("title", "来自数据库的标题");
    dataModel.put("content", getDatabaseContent());

    Template template = freemarkerConfig.getTemplate("document.ftl");
    String processedHtml = FreeMarkerTemplateUtils.processTemplateIntoString(template, dataModel);

    // 将HTML转换为Word文档(此处简化处理,实际可能需要使用Apache POI等库)
    byte[] wordBytes = convertHtmlToWord(processedHtml);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDispositionFormData("attachment", "document.docx");

    return new ResponseEntity<>(wordBytes, headers, HttpStatus.OK);
}

private List<Map<String, String>> getDatabaseContent() {
    // 此处模拟从数据库获取数据
    return Arrays.asList(
            Map.of("header", "数据库章节一", "text", "数据库内容一"),
            Map.of("header", "数据库章节二", "text", "数据库内容二")
    );
}

// 简化的HTML转Word逻辑,实际应用中可能需要更复杂的转换过程
private byte[] convertHtmlToWord(String html) {
    // 这里省略了HTML转Word的具体实现,可以使用第三方库如Apache POI等
    return html.getBytes(); // 这只是示例,实际返回的应该是Word文档的字节流
}
}

总结

通过上述步骤,我们使用Spring Boot与FreeMarker成功构建了一个简单的应用,能够根据模板和数据库数据动态生成Word文档并提供下载。实际应用中,你可能需要引入额外的库(如Apache POI等)来更精确地控制Word文档的样式和结构,以及更高效地处理HTML到Word的转换过程。此外,确保处理好模板的安全性,避免注入攻击等问题。

相关推荐
fenghuo_yuanma2 小时前
如何在IIS6,7中部署ASP.NET网站
后端·asp.net·网站部署
地瓜伯伯2 小时前
HandlerMethodArgumentResolver :深入spring mvc参数解析机制
大数据·人工智能·spring boot·spring·语言模型
亿只王菜菜3 小时前
WebRtc实现1V1音视频通话
spring boot·websocket·webrtc·实时音视频
小果子^_^7 小时前
springboot调用wsdl接口
java·spring boot·后端·wsdl
城市的稻草人VS8 小时前
rust 终端显示综合例程
开发语言·后端·rust
工业互联网专业9 小时前
基于springboot+vue+uniapp的语言课学习系统小程序
vue.js·spring boot·小程序·uni-app·毕业设计·源码
ing657689 小时前
基于weixin小程序校园快递系统的设计
java·spring boot·后端·mysql·课程设计
Dragon Wu11 小时前
SpringCloud OpenFeign 踩坑总结
java·spring boot·后端·spring cloud·微服务
椰汁3311 小时前
随机文章生成器:Node.js与JSON数据的创意碰撞
javascript·后端·面试
烦 啊12 小时前
go Channel原理 (三)
开发语言·后端·golang