1.引入依赖
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.2.0</version>
</dependency>
2.<第一种方法:有模板>
模板为
创建工具类在easypoi基础上进行封装
public class ExportUtil {
public static Workbook export(String canonicalPath, Map<String,Object> map){
TemplateExportParams params=new TemplateExportParams(canonicalPath,true);
return ExcelExportUtil.exportExcel(params,map);
}
public static void downExcel(HttpServletResponse response, String fileName, Workbook workbook) throws IOException {
try {
try {
fileName= URLEncoder.encode(fileName+".xlsx","UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" +fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
ServletOutputStream os = response.getOutputStream();
workbook.write(os);
os.flush();
os.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
写接口 前端传过来多个id然后找到对应数据并进行处理之后再封装进map中(这里默认文件名需要设置成英文否则会乱码)
@NoToken
@ApiOperation("导出点检单")
@GetMapping("/excel")
public void excelInspection(InspectionExcelDTO dto, HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
String templateUrl="template/inspection.xlsx";
//获取导出数据
List<InspectionExcelVO> retList = inspectionService.getExportList(dto);
Map<String,Object> data=new HashMap<>();
data.put("mapList",retList);
Workbook workbook = ExportUtil.export(templateUrl, data);
String filename="inspection";
ExportUtil.downExcel(response,filename,workbook);
}catch (Exception ex){
log.info("导出失败");
ex.printStackTrace();
}
}
利用postman测试
经测试没有问题(有模板这种有个好处是可以导出为多个sheet,不用多次去导出)