public static void test(HttpServletRequest request, HttpServletResponse response) {
try {
OutputStream out = null;
BufferedOutputStream bos = null;
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String fileName = "测试导出1.xls";
if (StringUtils.contains(request.getHeader("USER-AGENT"), "Firefox") || request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
} else {
fileName = URLEncoder.encode(fileName, "UTF-8");
}
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
out = response.getOutputStream();
bos = new BufferedOutputStream(out);
ClassPathResource cpr = new ClassPathResource("excel" + File.separator + "key_population_loan.xls");
ExcelWriter excelWriter = EasyExcel.write(bos)
// .registerWriteHandler(new CustomHandler())
.withTemplate(cpr.getInputStream()).excelType(ExcelTypeEnum.XLS).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
// List list = new ArrayList<>();
// for (int i = 0; i < 100; i++) {
// Test test = new Test();
// test.setJd("jd==" + i);
// test.setXh(i + 1 + "");
// test.setXj(1987 + i + "");
// test.setZycd(8765 + i + "");
// list.add(test);
// }
// FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
//
// excelWriter.fill(list, fillConfig, writeSheet);
Map<String, Object> map = new HashMap<>();
map.put("date", "2020年10月9日13:28:28");
map.put("area", "合肥市");
map.put("value", "76543");
excelWriter.fill(map, writeSheet);
// 别忘记关闭流
excelWriter.finish();
bos.flush();
bos.close();
} catch (Exception e) {
log.info(e.getMessage());
// 重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map = new HashMap<>(16);
map.put("status", "failure");
map.put("message", "下载文件失败" + e.getMessage());
try {
response.getWriter().println(JSON.toJSONString(map));
} catch (IOException ex) {
log.error(CommConstants.getExceptionInfo(ex));
}
}
}