只贴出controller部分,之前遇到问题是页面确实只请求了一次但是controller却执行了两次,后来自己摸索后原来问题出在没有指定ContentLength
@RequestMapping(value = "/exportExcel", method = RequestMethod.GET) public void exportExcel(Integer companyCode, Integer channelCode, String from, String to, HttpServletResponse response) { DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd"); Date fromDate = null; if (StringUtils.isNotBlank(from)) { fromDate = dtf.parseDateTime(from).toDate(); } Date toDate = null; if (StringUtils.isNotBlank(to)) { toDate = dtf.parseDateTime(to).toDate(); } try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();) { Workbook workbook = smsMoService.exportExcel(companyCode, channelCode, fromDate, toDate); workbook.write(byteArrayOutputStream); String fileName = URLEncoder.encode("上行短信.xlsx", "UTF-8"); response.reset(); response.addHeader("Content-Disposition", "attachment;filename=" + fileName); response.setContentType("application/vnd.ms-excel"); response.setContentLength(byteArrayOutputStream.size()); try (InputStream is = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); OutputStream os = response.getOutputStream() ) { IOUtils.copy(is, os); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } }