本文章只贴Excel导出在ssm中流程代码,在网上几乎没看到完整的代码所以贴一套流程
前端代码很简单就一个get请求即可
window.location.href = "${basePath}excelOut"
@GetMapping("excelOut") public ModelAndView excelOut() throws IOException { response.reset(); //清除buffer缓存 // 指定下载的文件名,浏览器都会使用本地编码,即GBK,浏览器收到这个文件名后,用ISO-8859-1来解码,然后用GBK来显示 // 所以我们用GBK解码,ISO-8859-1来编码,在浏览器那边会反过来执行。 response.setHeader("Content-Disposition", "attachment;filename=" + new String("标题.xlsx".getBytes("GBK"),"ISO-8859-1")); //如果使用该ContentType则浏览器自动下载到默认下载地址 // response.setContentType("application/vnd.ms-excel;charset=UTF-8"); //如果使用这两行代码则浏览器会弹出另存为的弹窗 response.setHeader("Content-Type","application/force-download"); response.setContentType("application/x-download;charset=UTF-8"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); XSSFWorkbook book = new XSSFWorkbook(); XSSFSheet sheet = book.createSheet("sheet"); Row row = sheet.createRow(0); row.createCell(0).setCellValue("01013352"); OutputStream output = null; BufferedOutputStream bufferedOutPut = null; try { output = response.getOutputStream(); bufferedOutPut = new BufferedOutputStream(output); // 执行 flush 操作, 将缓存区内的信息更新到文件上 bufferedOutPut.flush(); // 将最新 的 Excel 文件写入到文件输出流中,更新文件信息 book.write(bufferedOutPut); } catch (Exception e) { logger.error("导出excel异常",e); throw e; }finally { if(output!=null){ output.close(); } if(bufferedOutPut!=null){ // 关闭输出流对象 bufferedOutPut.close(); } } return null; }
如果选择另存为的弹窗后浏览器并没有弹出弹窗而是直接下载,
那么请到浏览器中的设置看看是否勾选了下载另存