1、引入jar包
<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、编写Excel工具类
public class ExcelUtils {
public static void exportExcel(TemplateExportParams templatePath, Map<String, Object> map, String fileName, HttpServletResponse response) throws IOException, CommonException {
Workbook workbook = ExcelExportUtil.exportExcel(templatePath, map);
downLoadExcel(fileName, response, workbook);
}
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws CommonException {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
workbook.write(response.getOutputStream());
} catch (IOException e) {
throw new CommonException( e.getMessage(), CommonExceptionDefinition.EXCEI_EXCEPTION);
}
}
}
3、编写导出接口
@GetMapping("/exportExcel")
public void exportExcel(String id, HttpServletResponse response) {
try {
TemplateExportParams templatePath = new TemplateExportParams("D:/excel/模板.xlsx");
Map<String, Object> map = new HashMap<>();
map.put("className", "三年二班");
map.put("teacher", "温老师");
map.put("studentList", studentList);
ExcelUtils.exportExcel(templatePath, map, "文件名.xlsx", response);
} catch (Exception ex) {
log.error("导出Excel记录出错:", ex);
}
}
4、编写导出模板,并放到对应目录

网友评论