SpringBoot实现下载excel模板文件

版权声明:本文为博主原创文章,欢迎转载,转载请注明作者、原文超链接 ,博主地址:https://blog.csdn.net/qq_31122833。 https://blog.csdn.net/qq_31122833/article/details/82384048

页面代码:

<input type="button" class="btn_default" onclick="downloadTemplate();" value="下载模板"/>
function downloadTemplate() {
        window.location.href=path+"/web/api/excel/open/downloadTemplate?accessToken=${accessToken}"
    }

后台代码如下:

/**
     * 下载excel模板
     *
     * @param response
     */
    @ResponseBody
    @RequestMapping("/open/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response, HttpSession session) {
        try {
            InputStream inputStream = (InputStream) this.getClass().getClassLoader().getResourceAsStream("base.xlsx");
            response.setContentType("application/zip");
            OutputStream out = response.getOutputStream();
            response.setHeader("Content-Disposition", "attachment; filename="+"base"+".xlsx");
            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();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("模板下载失败");
        }
    }

其中,base.xlsx文档就在项目的Resources目录下

猜你喜欢

转载自blog.csdn.net/qq_31122833/article/details/82384048