Java Controller层下载指定Excel模板

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012417405/article/details/83855715

     /**
      * 下载模板
      * @param request
      * @param response
      */
    @RequestMapping(value="template")
    public void template(HttpServletRequest request,HttpServletResponse response ){
        try {

            //指定需要下载的文件路径
            String downLoadPath ="E:"+File.separator+"upload"+File.separator+"template"+File.separator+"file_template.xlsx";
            String fileName=downLoadPath.substring(downLoadPath.lastIndexOf("/")+1);
            byte[] buffer=null;  
            buffer = downFileByte(downLoadPath) ; 
            String fileSuffixName=   fileName.substring(fileName.lastIndexOf(".")+1);
            response.reset(); //清除缓存
            response.setContentType("application/" +fileSuffixName + ";" +"charset = UTF-8"); //设置字符集和文件后缀名
       
            String name="历史项目模板";
            name = new String(name.getBytes(), "ISO-8859-1");
            response.setHeader("Content-Disposition","attachment; filename=" +name+"."+fileSuffixName); // 设置文件名称
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());  
            toClient.write(buffer);  
            toClient.flush();  
            toClient.close();
        } catch (Exception e) {
            e.printStackTrace();
            Log4jUtil.getLog4jUtil().error("下载模板"+e.getMessage());
        }
    }

    /** 
     * 下载文件 
     * 返回byte[] 
     * @param fileName 需要下载的文件名 
     * @return 
     * @throws Exception 
     */  
    public static byte[] downFileByte(String downLoadPath) throws Exception{  
        byte[] return_arraybyte=null;  
        InputStream ins=new FileInputStream(downLoadPath );  
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();  
        byte[] buf = new byte[1024];  
        int bufsize = 0;  
        while ((bufsize = ins.read(buf, 0, buf.length)) != -1) {  
            byteOut.write(buf, 0, bufsize);  
        }  
        return_arraybyte = byteOut.toByteArray();  
        byteOut.close();  
        ins.close();  
    return return_arraybyte;  
    }

注意:1.返回值一定要是void;2.如果下载文件名称中文乱码了,建议用时间戳命名.

猜你喜欢

转载自blog.csdn.net/u012417405/article/details/83855715