1、后端实现
1.创建用于映射模板的实体类
@Data
public class SysUserTo{
@Pattern(regexp = "^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$", message = "邮箱格式有误")
@Size(max = 50, message = "邮箱超出50长度")
@NotNull(message = "邮箱")
@ExcelProperty(value = "email", index = 0)
private String email;
// @Size(max = 5, message = "姓名超出5长度")
// @NotNull(message = "姓名")
// @ExcelProperty(value = "name", index = 1)
// private String name;
//
// @Size(max = 2, message = "昵称超出2长度")
// @NotNull(message = "昵称")
// @ExcelProperty(value = "nickname", index = 2)
// private String nickname;
}
2.引入easyexcel依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.2</version>
</dependency>
3.控制器类编写下载接口
@ApiOperation("Excel模板下载")
@GetMapping("/downTemplate")
public void downTemplate(HttpServletResponse response) throws IOException {
// 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
response.setContentType("application/vnd.ms-excel");
// response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("用户导入模板", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");
List<SysUserTo> list = new ArrayList<SysUserTo>();
SysUserTo downloadData = new SysUserTo();
downloadData.setEmail("[email protected]");
list.add(downloadData);
EasyExcel.write(response.getOutputStream(), SysUserTo.class).sheet("Sheet1")
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) //添加自适应列宽度
.doWrite(list);
}
}
2、前端实现
1.添加下载按钮
<el-button type="success" size="mini" icon="el-icon-download" @click="downTemplate">Excel模版下载</el-button>
2.发送下载请求
methods: {
downTemplate() {
return request({
url: `${api_name}/downTemplate`,
method: 'get',
responseType: 'blob'
}).then(response => {
this.$message.success('模板下载成功')
})
}
}
3.测试