public ResponseEntity<FileSystemResource> export(File file) { if (file == null) { return null; } HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".xls"); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); headers.add("Last-Modified", new Date().toString()); headers.add("ETag", String.valueOf(System.currentTimeMillis())); return ResponseEntity .ok() .headers(headers) .contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(new FileSystemResource(file)); }
@RequestMapping("/getExcel") public ResponseEntity<FileSystemResource> getUserExcel(@RequestParam(required=false) String fromId,@RequestParam(required=false) String type) throws Throwable { logger.debug("获取用户excel参数:fromId=",fromId); Children children = depthFindParentId(fromId, new Children()); File file = getExcelFile(children); return export(file); }
亲测可用
加一个递归函数:
public Children depthFindParentId( String parentId,Children child) throws Throwable { Children children = _ucApi.findChildren( parentId, true, true, true, null); child.getUsers().addAll(children.getUsers()); //用户 child.getDepartments().addAll(children.getDepartments());//部门 if (children.getDepartments().size() > 0) { for (Department dep : children.getDepartments()) { depthFindParentId(dep.getId(),child); } } return child; }
文件不落地
@RequestMapping("/excelExample") public ResponseEntity<byte[]> excel() throws IOException { // 创建工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); // 创建用户工作表 HSSFSheet sheet = workbook.createSheet("用户列表"); HSSFRow rows = sheet.createRow(0); rows.createCell(0).setCellValue("用户ID"); rows.createCell(1).setCellValue("姓名"); rows.createCell(2).setCellValue("手机号"); rows = sheet.createRow(0); rows.createCell(0).setCellValue("栏目ID"); rows.createCell(1).setCellValue("栏目名称"); sheet = workbook.createSheet("部门列表"); rows = sheet.createRow(0); rows.createCell(0).setCellValue("部门ID"); rows.createCell(1).setCellValue("部门名称"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { workbook.write(outputStream); } catch (IOException e) { e.printStackTrace(); } finally { outputStream.close(); } HttpHeaders httpHeaders = new HttpHeaders(); String fileName = new String("用户部门.xls".getBytes("UTF-8"), "iso-8859-1"); httpHeaders.setContentDispositionFormData("attachment", fileName); httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); ResponseEntity<byte[]> filebyte = new ResponseEntity<byte[]>(outputStream.toByteArray(), httpHeaders, HttpStatus.CREATED); try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } finally { outputStream.close(); } return filebyte; }