//导出
@GetMapping("/exportData")
public void exportData(HttpServletResponse response) {
categoryService.exportData(response);
}
//导出
@Override
public void exportData(HttpServletResponse response) {
try {
//1 设置响应头信息和其他信息
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("分类数据", "UTF-8");
//设置响应头信息 Content-disposition
response.setHeader("Content-disposition","attachment;filename="+fileName+".xlsx");
//2 调用mapper方法查询所有分类,返回list集合
List categoryList = categoryMapper.findAll();
//最终数据list集合
List categoryExcelVoList = new ArrayList<>();
// List -- List
for(Category category : categoryList) {
CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
//把category值获取出来,设置到categoryExcelVo里面
// Long id = category.getId();
// categoryExcelVo.setId(id);
BeanUtils.copyProperties(category,categoryExcelVo);
categoryExcelVoList.add(categoryExcelVo);
}
//3 调用EasyExcel的write方法完成写操作
EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class)
.sheet("分类数据").doWrite(categoryExcelVoList);
}catch (Exception e) {
e.printStackTrace();
throw new GuiguException(ResultCodeEnum.DATA_ERROR);
}
}