1.controller层,value中的名字是自定义的,在controller层写之前要建好query和service层和vo层,如果不知道上述是什么意思,请再学习一下springMvc ,在这就不一一赘述。
@PostMapping(value = "expoet")
@ApiOperation(value = "导出", notes = "导出", produces = MediaType.APPLICATION_JSON_VALUE)
public void export(@RequestBody TestQuery query, HttpServletResponse response) throws IOException {
TestService.export(query, response);
}
2.service层
/**
*
*导出
*
**/
void export(TestQuery query, HttpServletResponse response) throws IOException;
3.impl层,实体类,在这用到的 getExcelOutputStream()是自己封装的方法,后面加文件名和格式
@Override
public void export(TestQuery query, HttpServletResponse response) throws IOException {
//设置返回文件名称和格式
getExcelOutputStream("导出表", response);
if (CollectionUtils.isNotEmpty(query)) {
try (OutputStream outputStream = response.getOutputStream()) {
EasyExcel.write(outputStream, TestVo.class)
.sheet("导出表").doWrite(query);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
4.getExcelOutputStream()方法,主要解决用utf-8返回防止乱码
/**
* 导出文件时为Writer生成OutputStream
* @param fileName: 文件名称
* @param response:
*/
public static void getExcelOutputStream(String fileName,
HttpServletResponse response) throws IOException {
try {
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "max-age=0");
// response.setHeader("content-Type", "application/vnd.ms-excel");
} catch (IOException e) {
throw new IOException("导出excel表格失败!", e);
}
}
5.vo层,这里是TestVo,导出的字段要加一个注释
@ExcelProperty(value = "名称")
private String name;
这样用postman调用就可以生成excel表格了。当然导出的方法千千万,这只是其中一种最简单的。
共勉!