答:
public static void exportExcel(Class clazz, List list, String sheetName, HttpServletResponse response) throws IOException {
try {
response.setContentType("application/vnd.ms-excel;" + GlobalConstant.CHARSET_UTF8);
response.setCharacterEncoding(GlobalConstant.UTF8);
String fileName = URLEncoder.encode(sheetName, GlobalConstant.UTF8).replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), clazz)
.autoCloseStream(Boolean.FALSE)
.sheet(sheetName)
.doWrite(list);
} catch (Exception e) {
// 重置response
response.reset();
response.setContentType(GlobalConstant.APPLICATION_JSON_VALUE);
response.setCharacterEncoding(GlobalConstant.UTF8);
Map<String, Object> map = new HashMap<>();
map.put("status", 500);
map.put("message", "下载文件失败" + e.getMessage());
response.getWriter().println(JSON.toJSONString(map));
}
}