使用springboot实现excel下载

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

使用springboot实现excel下载

提示:以下是本篇文章正文内容,下面案例可供参考

一、使用步骤

1.yml

在D盘下放你要下载的excel文件

templates:
  whitepath: D:\\template.xlsx

2.controller

 @RequestMapping("/download")
    public CommRetVo downloadWorkHourRecordTemplate(HttpServletResponse response) {
        CommRetVo commRetVo = new CommRetVo();
        try {
//            Resource resource = new ClassPathResource("static/excelTemplate/template.xlsx");\
           // Resource resource = new ClassPathResource(templateswhitepath);
            File file = new File(templateswhitepath);
            String filename = "template.xlsx";
            InputStream inputStream = new FileInputStream(file);
            //强制下载不打开
            response.setContentType("application/force-download");
            OutputStream out = response.getOutputStream();
            //使用URLEncoder来防止文件名乱码或者读取错误
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            int b = 0;
            byte[] buffer = new byte[1000000];
            while (b != -1) {
                b = inputStream.read(buffer);
                if (b != -1) {
                    out.write(buffer, 0, b);
                }
            }
            inputStream.close();
            out.close();
            out.flush();
            commRetVo.setCode("1");
            commRetVo.setMsg("下载成功");

        } catch (IOException e) {

            e.printStackTrace();
            commRetVo.setCode("0");
            commRetVo.setMsg("失败");
        }
        return commRetVo;
    }

总结

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值