1.引入hutool和相关依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.0.7</version>
</dependency>
<!--必需引入下面的poi-ooxml依赖而且版本要》=3.17才行,因为Hutool工具ExcelUtil依赖这个 https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.1</version>
</dependency>
2.创建User实体
public class User {
private String name;
private Integer age;
public User() {
}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
3.编写controller层
@Controller
public class OutputExcelController {
@RequestMapping("/export")
@ResponseBody
public void export(HttpServletResponse response) {
List<User> list = new ArrayList<>();
list.add(new User("zhangsan", 22));
list.add(new User("zhangsan1", 23));
list.add(new User("zhangsan2", 24));
list.add(new User("zhangsan3", 25));
list.add(new User("zhangsan4", 26));
list.add(new User("zhangsan5", 27));
// 通过工具类创建writer,默认创建xls格式
ExcelWriter writer = ExcelUtil.getWriter();
//自定义标题别名
writer.addHeaderAlias("name", "姓名");
writer.addHeaderAlias("age", "年龄");
// 合并单元格后的标题行,使用默认标题样式(lastColumn应为用户属性个数-1)
writer.merge(1, "申请人员信息");
// 一次性写出内容,使用默认样式,强制输出标题
writer.write(list, true);
//response为HttpServletResponse对象
response.setContentType("application/vnd.ms-excel;charset=utf-8");
//college是弹出下载对话框的文件名,不能为中文,中文请自行编码
// String name = StringUtils.toUtf8String("学院");
String name = "college";
response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xls");
ServletOutputStream out = null;
try {
//out为OutputStream,需要写出到的目标流
out = response.getOutputStream();
writer.flush(out, true);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭writer,释放内存
writer.close();
}
//此处记得关闭输出Servlet流
IoUtil.close(out);
}
}
4.编写前端页面来访问export接口导出Excel表格
templates下创建一个export.html在body里通过一个超链接“导出Excel”去访问后端的export接口导出Excel表格(直接在浏览器输入接口地址也能导出Excel表)
<!DOCTYPE html>
最后值得一提的是前端直接用layui框架开启导出功能就能导出Excel表不需要编写后端代码,具体做法参考layui官方示例https://www.layui.com/demo/table/toolbar.html
进行预览和查看代码