java下载模版Excel

/**
     * 模版下载
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/fileTemplateDownLoad")
    public void fileDownLoadAutoBatch(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String exportType = request.getParameter("exportType");
        Assert.notNull(exportType, "exportType cannot be null");
        String templateName = ""; //文件名
        String templatePath = ""; //下载模板
        if("02".equals(exportType)){
            templateName = "a导入模板.xlsx";
            templatePath = "template/a导入模板.xlsx";
        }
        if("01".equals(exportType)){
            templateName = "b导入模板.xlsx";
            templatePath = "template/b导入模板.xlsx";
        }


        String fileRealPath = request.getRealPath(templatePath);
        String newFileName = null;
        try {
            // 这里URLEncoder.encode可以防止中文乱码
            newFileName = URLEncoder.encode(templateName, "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + newFileName);
        // 服务器告诉浏览器它发送的数据属于什么文件类型,也就是响应数据的MIME类型
        //response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 关闭缓存(HTTP/1.1)
        response.setHeader("Cache-Control", "no-store");
        // 关闭缓存(HTTP/1.0)
        response.setHeader("Pragma", "no-cache");
        // 缓存有效时间
        response.setDateHeader("Expires", 0);

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            // 读取文件的输入流
            inputStream  = new FileInputStream(fileRealPath);
            XSSFWorkbook wb = new XSSFWorkbook(inputStream);
            outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            System.out.println("文件输出错误!");
            e.printStackTrace();
        } finally {
            IoUtil.close(inputStream);
            IoUtil.close(outputStream);
        }

    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值