Spring Boot 集成 FreeMarker 详解案例

“年轻就不应该让自己过得太舒服” – From yong

一、Springboot 那些事

SpringBoot 很方便的集成 FreeMarker ,DAO 数据库操作层依旧用的是 Mybatis,本文将会一步一步到来如何集成 FreeMarker 以及配置的详解:

Springboot 那些事:

系类文章:

《Spring Boot 之 RESRful API 权限控制》

《Spring Boot 之 HelloWorld 详解》

《Springboot 整合 Mybatis 的完整 Web 案例》

《Springboot 实现 Restful 服务,基于 HTTP / JSON 传输》

《Springboot 集成 FreeMarker》

二、运行 springboot-freemarker 工程

git clone 下载工程 springboot-learning-example ,项目地址见 GitHub – https://github.com/JeffLi1993/springboot-learning-example。下面开始运行工程步骤(Quick Start):

1. 数据库准备

a. 创建数据库 springbootdb:

b. 创建表 city :(因为我喜欢徒步)

<

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot集成Freemarker导出Excel可以通过以下几个步骤来实现: 1. 添加依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 2. 创建Freemarker模板 创建一个freemarker模板,用于指定导出的excel文件的格式和样式。例如,可以创建一个名为`template.ftl`的模板文件,其中包含以下内容: ```html <table> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>地址</th> </tr> </thead> <tbody> <#list users as user> <tr> <td>${user.name}</td> <td>${user.age}</td> <td>${user.gender}</td> <td>${user.address}</td> </tr> </#list> </tbody> </table> ``` 3. 创建Controller 创建一个Controller,用于接收请求并生成excel文件。例如,可以创建一个名为`ExportController`的Controller,其中包含以下代码: ```java @Controller public class ExportController { @Autowired private Configuration freemarkerConfig; @RequestMapping("/export") public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception { // 设置响应头 response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=users.xls"); // 获取模板 Template template = freemarkerConfig.getTemplate("template.ftl"); // 创建数据模型 Map<String, Object> model = new HashMap<String, Object>(); List<User> users = getUserList(); model.put("users", users); // 生成excel文件 Writer out = response.getWriter(); template.process(model, out); out.flush(); out.close(); } private List<User> getUserList() { List<User> users = new ArrayList<User>(); // 添加测试数据 users.add(new User("张三", 25, "男", "北京市海淀区")); users.add(new User("李四", 30, "女", "上海市浦东新区")); users.add(new User("王五", 35, "男", "广州市天河区")); users.add(new User("赵六", 40, "女", "深圳市福田区")); return users; } } ``` 4. 运行程序 启动Spring Boot应用程序,并访问`/export`路径即可下载生成的excel文件。 以上就是通过Spring Boot集成Freemarker导出Excel的步骤。需要注意的是,本例中使用的是xls格式的excel文件,如果需要使用xlsx格式,需要将poi-ooxml依赖修改为poi-ooxml-schemas。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值