一、EasyExcel写操作使用
①实体类(加上注解,也就是生成的excel中的列名)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExcelCategoryVo {
@ExcelProperty("分类id")
private Long id;
@ExcelProperty("分类名")
private String name;
@ExcelProperty("描述")
private String description;
@ExcelProperty("状态:(0正常,1禁用)")
private String status;
}
②请求
@GetMapping("/category/export")
public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {
try {
//设置响应的请求头
WebUtils.setDownLoadHeader("分类.xlsx",response);
//获取需要导出的数据(从数据库查)
List<Category> categories = categoryService.list();
List<ExcelCategoryVo> excelCategoryVos = BeanCopyUtils.copyBeanList(categories, ExcelCategoryVo.class);
//将数据导入excel中,这里需要设置不关闭流
EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class).autoCloseStream(Boolean.FALSE).sheet("分类导出")
.doWrite(excelCategoryVos);
} catch (Exception e) {
// 重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map = MapUtils.newHashMap();
map.put("status", "failure");
map.put("message", "下载文件失败" + e.getMessage());
response.getWriter().println(JSON.toJSONString(map));
}
}
③工具类(设置响应的请求头)
public static void setDownLoadHeader(String filename, HttpServletResponse response) throws UnsupportedEncodingException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
String fname= URLEncoder.encode(filename,"UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition","attachment; filename="+fname);
}