栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

使用springboot实现excel下载

Java 更新时间:发布时间: 百科书网 趣学号

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

文章目录
  • 前言
  • 一、使用步骤
    • 1.yml
    • 2.controller
  • 总结


前言

使用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;
    }
总结
转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/956700.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号