java导出多个excel,以压缩包下载

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

需求:一次请求,导出多个excel
思路:
1.java servlet一个请求,只能返回一个输出流,所以一次只能导出一个excel;
2.如果一次需要导出多个excel,可以在本地生成多个excel,然后压缩成压缩包,然后下载压缩包;
步骤:
1.在本地创建一个零时文件夹,将多个excel生成到该文件夹下;
2.将该文件夹压缩,导出;
3.将该文件夹删除;

上代码:

//以模板形式生成excel
@RequestMapping(value = "映射路径")
public void exportDetail(HttpServletResponse response, HttpServletRequest request)throws ParseException, ParsePropertyException, InvalidFormatException, IOException {
    // 模板在项目存放位置
        String fileRootPath = request.getSession().getServletContext().getRealPath("/templates");
    // 模板文件名称
    String fileName = "";
    // 将excel导出的文件位置
    String filePath = 在本地创建好的文件夹路径 + File.separator;
    // 得到此路径下文件
    File fileDir = new File(filePath);
    //创建文件夹
    if (!fileDir.exists() && !fileDir.isDirectory()) {
        fileDir.mkdirs();
    }
   // 用于存放生成的excel文件名称
    List<String> fileNames = new ArrayList<String>();
    // 导出Excel文件路径
    String fullFilePath = "";
    //输入流
    InputStream in = null;
    //输出流
    FileOutputStream os = null;
    //循环导出excel到临时文件夹中
    for (int i = 0; 根据需求亲确定导出几次; i++) {
    // 往excel填入内容
    Map<String, Object> bean = new HashMap<String, Object>();
    bean.put("需要遍历的内容", xxxx);
    //每次导出的excel的文件名
    String fileNameS = "xxxxx.xls";
    if (bean != null) {
    //XLSTransformer生成excel文件
    XLSTransformer transformer = new XLSTransformer();
    in = new FileInputStream(new File(fileRootPath + File.separator + fileName));
    HSSFWorkbook workbook;
    // 设置sheet页名称
    String sheetName = "详细";
    workbook = (HSSFWorkbook) transformer.transformXLS(in, bean);
    // 设置sheet页名称
    workbook.setSheetName(0, sheetName);
    // 导出excel的全路径
    fullFilePath = filePath + File.separator + fileNameS;
    fileNames.add(fullFilePath);
    os = new FileOutputStream(fullFilePath);
    // 写文件
    workbook.write(os);
    }
    //清空流缓冲区数据
    os.flush();
    //关闭流
    os.close();
    in.close();
    os = null;
    }

    //导出压缩文件的全路径  
    String zipFilePath = filePath + "压缩文件名"+".zip";
    //导出zip
    File zip = new File(zipFilePath);
    //将excel文件生成压缩文件  
    File srcfile[] = new File[fileNames.size()];    
     for (int j = 0, n1 = fileNames.size(); j < n1; j++) {    
         srcfile[j] = new File(fileNames.get(j));    
     }    
       ZipFiles(srcfile, zip);
     response.setContentType("application/zip");
        response.setHeader("Location",zip.getName());
        response.setHeader("Content-Disposition", "attachment; filename=" + zip.getName());  
        OutputStream outputStream = response.getOutputStream();
        InputStream inputStream = new FileInputStream(zipFilePath);
        byte[] buffer = new byte[1024];
        int i = -1;
        while ((i = inputStream.read(buffer)) != -1) {
           outputStream.write(buffer, 0, i);
         }
        outputStream.flush();
        outputStream.close();
        inputStream.close();
        outputStream = null;

       try {  
            delAllFile(filePath); // 删除完里面所有内容  
            filePath = filePath.toString();  
            java.io.File myFilePath = new java.io.File(filePath);  
            myFilePath.delete(); // 删除空文件夹  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }


    //压缩文件    
    public void ZipFiles(File[] srcfile, File zipfile) {    
        byte[] buf = new byte[1024];    
        try {    
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(    
                    zipfile));    
            for (int i = 0; i < srcfile.length; i++) {    
                FileInputStream in = new FileInputStream(srcfile[i]);    
                out.putNextEntry(new ZipEntry(srcfile[i].getName()));    
                int len;    
                while ((len = in.read(buf)) > 0) {    
                    out.write(buf, 0, len);    
                }    
                out.closeEntry();    
                in.close();    
            }    
            out.close();    
        } catch (IOException e) {    
            e.printStackTrace();    
        }    
    }  


    /*** 
     * 删除指定文件夹下所有文件 
     *  
     * @param path 文件夹完整绝对路径 
     * @return 
     */  
    public static  boolean delAllFile(String path) {  
        boolean flag = false;  
        File file = new File(path);  
        if (!file.exists()) {  
            return flag;  
        }  
        if (!file.isDirectory()) {  
            return flag;  
        }  
        String[] tempList = file.list();  
        File temp = null;  
        for (int i = 0; i < tempList.length; i++) {  
            if (path.endsWith(File.separator)) {  
                temp = new File(path + tempList[i]);  
            } else {  
                temp = new File(path + File.separator + tempList[i]);  
            }  
            if (temp.isFile()) {  
                temp.delete();  
            }  
            if (temp.isDirectory()) {  
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件  
                flag = true;  
            }  
        }  
        return flag;  
    }  

搞定!

猜你喜欢

转载自blog.csdn.net/qq_36675996/article/details/80815815