1.controller曾代码:
@GetMapping("/download-template")
@ApiOperation("获取导入模板")
public void downloadTemplate(HttpServletResponse response) throws IOException {
shopShelvesService.downloadTemplate(response);
}
2.service层代码:
public void downloadTemplate(HttpServletResponse response) throws IOException {
//设置返回头
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码
String fileName = URLEncoder.encode("角色导入模板", "UTF-8");
//设置下载的文件名
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//新建ExcelWriter
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
//获取第一个sheet对象
WriteSheet mainSheet = EasyExcel.writerSheet(0, "角色导入").head(UserRoleExcelVO.class).build();
//第一个sheet数据
List<UserRoleExcelVO> list = new ArrayList<>();
list.add(new UserRoleExcelVO("ZS001","张三","角色导入"));
list.add(new UserRoleExcelVO("LS001","李四","采购申请,采购审批"));
//向第一个sheet写入数据 若传入空list只导出表头
excelWriter.write(list,mainSheet);
//获取第二个sheet对象
WriteSheet detailSheet = EasyExcel.writerSheet(1, "角色模板").head(RoleTemplateVo.class).build();
//第二个sheet数据
List<RoleTemplateVo> roleTemplateList = new ArrayList<>();
roleTemplateList.add(new RoleTemplateVo("超级管理员"));
roleTemplateList.add(new RoleTemplateVo("租户管理员"));
//向第二个sheet写入数据
excelWriter.write(roleTemplateList,detailSheet);
//关闭流
excelWriter.finish();
}
3.实体类(excel列名):
@Data //@Data注解不需要写set和get方法,相当于@Getter @Setter @RequiredArgsConstructor @ToString
@AllArgsConstructor//有参构造
@NoArgsConstructor//无参构造
@HeadStyle(horizontalAlignment = HorizontalAlignment.CENTER)//表头样式
@ContentStyle(horizontalAlignment = HorizontalAlignment.CENTER)//内容样式
public class UserRoleExcelVO {
//列宽
@ColumnWidth(30)
//列名
@ExcelProperty("登录名称")
private String userName;
@ColumnWidth(30)
@ExcelProperty("用户名称")
private String nickName;
@ColumnWidth(50)
@ExcelProperty("用户角色(多个用英文,号隔开)")
private String role;
}
EasyExcel官方文档: EasyExcel官方文档
旧文档: 语雀
GitHub地址: GitHub地址
本文共 203 个字数,平均阅读时长 ≈ 1分钟
评论 (0)