Spring boot集成freemarker导出excel
时间: 2023-11-10 07:54:03 浏览: 45
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。