开发者

Java如何导出多个excel并打包压缩成.zip文件

目录
  • Java导出多个excel并打包压缩成.zip文件
    • 1、先获取到数据
    • 2、将导出的数据转成多个excel
    • 3、相关工具类
  • 总结

    Java导出多个excel并打包压缩成.zip文件

    1、先获取到数据

    并将数据导出excel到指定位置

     public void downPoliceZip(WorksitePoliceApiInfo worksitePoliceApiInfo) throws Exception {
            String zipName = "同步数据" + LocalDate.now() ;
            List<Map<String, Object>> workerMaps = new LinkedList<>();
            List<Map<String, Object>> worksiteMaps = new LinkedList<>();
            Map<String,Object > map = new LinkedHashMap<>();
            //获取数据
            .........
    //            String realPath = request.getSession().getServletContext().getContextPath();
                //创建临时文件夹保存excel
                String tempDir = zipPath + "/tempDir/" + LocalDate.now() + "/";
             
                //将导出的数据转成多个excel
                List<File> files = this.getStoreOrderExcels(tempDir, workerMaps, worksiteMaps, flag);
    
                //下载zip
                boolean tag = FileDownloadUtils.generateFile(tempDir, "zip", zipPath, zipName);
                //删除tempDir文件夹和其中的excel和zip文件
                boolean b = FileDownloadUtils.deleteDir(new File(zipPath + "\\tempDir"));
                if (!b) {
                    throw new RuntimeException("tempDir文件夹及其中的临时Excel和zip文件删除失败");
                }
        }
    

    2、将导出的数据转成多个excel

     /**
         * 将导出的数据转成多个excel
         *
         * @param tempDir      路径
         * @param workerMaps   map集合
         * @param worksiteMaps map集合
         * @param flag         标识
         * @return List<File>
         * @throws IOException 异常
         */
        private List<File> getStoreOrderExcels(String tempDir, List<Map<String, Object>> workerMaps, List<Map<String, Object>> worksiteMaps, String[] flag) throws IOException {
            FileDownloadUtils.createFile(tempDir);
            //存在多个文件
            List<File> files = new ArrayList<>();
            String path;
            for (int i = 0; i < flag.length; i++) {
                if (flag[i].equals("worker")) {
                    path = this.getStoreOrderExcel(flag[i], workerMaps, tempDir);
                } else {
                    path = this.getStoreOrderExcel(flag[i], worksiteMaps, tempDir);
                }
                //excel添加到files中
                files.add(new File(path));
            }
            return files;
        }
    
    /**
         * @param flag    标识
         * @param maps    map数组
         * @param tempDir 路径
         * @return String
         * @throws IOException 异常
         */
        public String getStoreOrderExcel(String flag, List<Map<String, Object>> maps, String tempDir) throws IOException {
            // 通过工具类创建writer,默认创建xls格式
            ExcelWriter writer = ExcelUtil.getWriter();
            if (flag.equals("worker")) {
                //自定义标题别名
                writer.addHeaderAlias("workerName", "姓名");
                writer.addHeaderAlias("workerIdcard", "身份证号");
            } else {
                //自定义标题别名
                writer.addHeaderAlias("workersiteName", "工地名称");
                writer.addHeaderAlias("worksiteAddress", "工地地址");
            }
            writer.write(maps, true);
    
            //生成一个excel
            String path = tempDir + LocalDate.now() + "_" + flag + ".xls";
    
            //本地测试下载
            FileOutputStream outputStream = new FileOutputStream(path);
            writer.flush(outputStream, true);
            writer.close();
            return path;
        }
    

    3、相关工具类

    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    
    public class FileDownloadUtils {
    
        /**
         * 创建文件夹;
         *
         * @param path 路径
         */
        public static void createFile(String path) {
            File file = new File(path);
            //判断文件是否存在;
            if (!file.exists()) {
                //创建文件;
                file.mkdirs();
            }
        }
    
        /**
         * 删除文件夹及文件夹下所有文件
         *
         * @param divFnOGr 文件地址
         * @return boolean
         */
        public static boolean deleteDir(File dir) {
            if (dir == null || !dir.exists()) {
                return true;
            }
            if (dir.isDirectory()) {
                String[] children = dir.list();
                //递归删除目录中的子目录下
                for (String child : children) {
                    boolean success = deleteDir(new File(dir, child));
                    if (!success) {
                        return false;
                    }
                }
            }
            // 目录此时为空,可以删除
            return dir.delete();
        }
    
        /**
         * @Description  将多个文件进行压缩到指定位置
         * @param path   要压缩的文件路径
         * @param format 生成的格式(zip、rar)
         * @param zipPath zip的路径
         * @param zipName zip文件名
         */
        public static boolean generateFile(String path, String format,String zipPath,String zipName) throws Exception {
    
            File file = new File(path);
            // 压缩文件的路径不存在
            if (!file.exists()) {
                throw new Exception("路径 " + path + " 不存在文件,无法进行压缩...");
            }
            // 用于存放压缩文件的文件夹
            String generateFile = zipPath + File.separator ;
            File compress = new File(generateFile);
            // 如果文件夹不存在,进行创建
            if( !pythoncompress.exists() ){
                compress.mkdirs();
            }
    
            // 目的压缩文件
            String generateFileName = compress.getAbsolutePath() + File.separator  + zipName + "." + format;
    
            // 输出流
            FileOutputStream outputStream = new FileOutput编程客栈Stream(generateFileName);
            // 压缩输出流
            ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream));
    
            //压缩
            generateFile(zipOutputStream,file,"");
            System.out.println("源文件位置:" + file.getAbsolutePath() + ",目的压缩文件生成位置:" + generateFileName);
            // 关闭 输出流
            zipOutputStream.close();
            return true;
        }
    
        /**
         * @param out  输出流
         * @param file 目标文件
         * @param dir  文件夹
         * @throws Exception
         */
        private static void generateFile(ZipOutputStream out, File file, String dir) throws Exception {
            // 当前的是文件夹,则进行一步处理
            if (file.isDirectory()) {
                //得到文件列表信息
                File[] files = file.listFiles();
                //将文件夹添加到下一级打包目录
                out.putNextEntry(new ZipEntry(dir www.devze.com+ "/"));
                dir = dir.length() == 0 ? "" : dir + "/";编程
                //循环将文件夹中的文件打包
                for (int i = 0; i < files.length; i++) {
                    generateFile(out, files[i], dir + files[i].getName());
                }
            } else { // 当前是文件
                // 输入流
                FileInputStream inputStream = new FileInputStream(file);
                // 标记要打包的条目
                out.putNextEntry(new ZipEntry(dir));
                // 进行写操作
                int len = 0;
                byte[] bytes = new byte[1024];
                while ((len = inputStream.read(bytes)) > 0) {
                    out.write(bytes, 0, len);
                }
                // 关闭输入流
                inputStream.close();
            }
        }
    

    总结

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。

    0

    上一篇:

    下一篇:

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    最新开发

    开发排行榜