controller:
@RequestMapping(value = "/exportToExcel")
public BaseResponse exportToExcel(HttpServletResponse response,QueryOrganizationListRequest query) throws IOException {
return new BaseResponse().success(excelService.exportToExcel(response,query));
}
service:
package com.qdeicc.credit.service;
@Service
public class OrganizationExcelService {
//...............
public void exportExcel(HttpServletResponse response, String title, Class head, List<TbOrganization> list) throws IOException {
exportExcel(response, title, head, list, null);
}
private void exportExcel(HttpServletResponse response, String title, Class head, List<TbOrganization> list, Set<String> set) {
try{
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode(title, StandardCharsets.UTF_8);
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
if(set == null){
EasyExcel.write(response.getOutputStream(), head).sheet("sheet")
.doWrite(list);
}else{
EasyExcel.write(response.getOutputStream(), head).includeColumnFiledNames(set).sheet("sheet")
.doWrite(list);
}
}catch (Exception e){
System.out.println("ERROR "+e.getMessage());
}
}
public BaseResponse exportToExcel(HttpServletResponse response, QueryOrganizationListRequest query) throws IOException {
try {
List<TbOrganization> organizationList = new ArrayList<>();
List<Map<String, Object>> allOrgTitleList = orgService.getAllOrgTitleList(query);
if (orgService.getTotalRecordCount() == 0) {
return new BaseResponse().error("数据库为空,导出失败");
}
for (Map<String, Object> org : allOrgTitleList) {
//逐条添加到数据库
}
exportExcel(response, "党政群机关", TbOrganization.class, organizationList);
return new BaseResponse().success("导出成功");
} catch (Exception e) {
return new BaseResponse().error("导出失败"+e.getMessage());
}
}
}