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; }