Excel表单的导入导出工具类(二)

前一节我们说了excel写入数据并导出。这一节说一下单独下载excel模板的操作。

1.controlle层

这里写图片描述

2.工具类:FileUtils.downloadFiles()

public static void downloadFiles(HttpServletResponse response ,String filePath){
    response.setContentType("application/octet-stream");
    response.setCharacterEncoding("utf-8");
    FileInputStream fs=null;
    OutputStream myout = null;
    try{
        File file=new File(filePath.trim());
        if(file.exists()){
            String fileName=file.getName();
            fs=new FileInputStream(file);
            response.addHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"utf-8"));
            buff=new BufferedInputStream(fs);
            byte[] b=new byte[1024];
            long k=0;
            myout=response.getOutputStream();
            while(k < file.length()){
                int j = buff.read(b,0,1024);
                k +=j;
                myout.write(b,0,j);
            }
            buff.close();
        }else{
            PrintWriter os = response.getWriter();
            os.write("文件不存在!");
            os.close();
        }
        if(myout != null){
            myout.flush();
            myout.close();
        }
        if(fs !=null){
            fs.close();
        }
    }catch(Exception e){
        logger.error(e);
    }finally{
        if(myout != null){
            try{
                myout.flush();
                myout.close();
            }catch(IOException e){
                logger.error(e);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/zhanglf02/article/details/79852528