基于ssm使用poi做导出的前端和Controller代码

本文章只贴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;
    }
如果选择另存为的弹窗后浏览器并没有弹出弹窗而是直接下载,
那么请到浏览器中的设置看看是否勾选了下载另存


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值