java創建excel表並同其他文件一起壓縮進壓縮包進行下載

java創建excel表並同其他文件一起壓縮進壓縮包進行下載

不多說,直接上代碼。

	public ServerResponse downloadFiles(Integer id) {
        if (id==null||"".equals(id)){
            return ServerResponse.createBySuccessMessage("請選擇要下載的文件");
        }
        List<ProjectResult> projectResult=projectUserMapper.getProject(id);//從數據庫獲取需要生成excel的數據
        List<List<String>> lists=new ArrayList<List<String>>();
        String[] label = getFormFile(projectResult, lists);//獲取excel表表頭

        String zipFileNameEn=null;
        String zipFilePath=null;
        List<String> fileName=new ArrayList<>();
        List<String> filePath=new ArrayList<>();
        zipFileNameEn = "生成excel名稱";
        try {
            zipFilePath = addFileExcel.createExcel(zipFileNameEn,"數據表",label,lists);//生成excel文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        fileName.add("物客一張表.xlsx");
        filePath.add(zipFilePath);
        downloadFiles(response,fileName,filePath,nasPath+"/exportFile",zipFileNameEn);
        //從文件夾刪除代碼生成的excel文件
        File file=new File(zipFilePath);
        file.delete();
        return ServerResponse.createBySuccessMessage(SuccessConstant.handleSuccess);
    }
    //生成excel文件並返回文件路徑
    public String createExcel(String fileName,String sheetName ,String[] label, List<List<String>> list ) throws IOException {
        Workbook wb = new XSSFWorkbook();
        Sheet stuSheet = wb.createSheet(sheetName);
        Row titleRow = stuSheet.createRow(0);
        CellStyle style = wb.createCellStyle();
        Cell cell = null;
        //把已經寫好的標題行寫入excel文件中
        for (int i = 0; i < label.length; i++) {
            cell = titleRow.createCell(i);
            cell.setCellValue(label[i]);
            cell.setCellStyle(style);
        }
        //把從數據庫中取得的數據一一寫入excel文件中
        Row row = null;
        List<String> stuList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            //創建list.size()行數據
            row = stuSheet.createRow(i + 1);
            //把值一一寫進單元格里
            //設置第一列爲自動遞增的序號
            for(int j=0;j<list.get(i).size();j++){
                row.createCell(j).setCellValue(list.get(i).get(j));
            }
        }
        //設置單元格寬度自適應,在此基礎上把寬度調至1.5倍
        for (int i = 0; i < label.length; i++) {
            stuSheet.autoSizeColumn(i, true);
            stuSheet.setColumnWidth(i, stuSheet.getColumnWidth(i) * 15 / 10);
        }
        //獲取配置文件中保存對應excel文件的路徑,本地也可以直接寫成F:excel/stuInfoExcel路徑
        String folderPath="/app/file/notice/files/temp/materialCard/";

        //創建上傳文件目錄
        File folder = new File(folderPath);
        //如果文件夾不存在創建對應的文件夾
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //設置文件名
        String fileNames = fileName + ".xlsx";
        String savePath = folderPath + File.separator + fileNames;
        // System.out.println(savePath);

        OutputStream fileOut = new FileOutputStream(savePath);
        wb.write(fileOut);
        fileOut.close();
        //返回文件保存全路徑
        return savePath;
    }
    //生成壓縮包文件並把所有文件壓縮進壓縮包進行下載
    public void downloadFiles(HttpServletResponse response, List<String> name,
                              List<String> paths,String directoryPath,
                              String zipFileNameEn) {

        java.io.File directoryFile=new java.io.File(directoryPath);
        if(!directoryFile.isDirectory() && !directoryFile.exists()){
            directoryFile.mkdirs();
        }
        //設置最終輸出zip文件的目錄+文件名
        SimpleDateFormat formatter  = new SimpleDateFormat("yyyyMMddHHmmss");
        String zipFileName =zipFileNameEn+".zip";
        String strZipPath = directoryPath+"/"+zipFileName;

        ZipOutputStream zipStream = null;
        FileInputStream zipSource = null;
        BufferedInputStream bufferStream = null;
        java.io.File zipFile = new java.io.File(strZipPath);
        try{
            //構造最終壓縮包的輸出流
            zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
            for (int i = 0; i<paths.size() ;i++){
                //解碼獲取真實路徑與文件名
                String realFilePath = java.net.URLDecoder.decode(paths.get(i),"UTF-8");
                java.io.File file = new File(realFilePath);
                if(file.exists())
                {
                    zipSource = new FileInputStream(file);//將需要壓縮的文件格式化爲輸入流
                    /**
                     * 壓縮條目不是具體獨立的文件,而是壓縮包文件列表中的列表項,稱爲條目,就像索引一樣這裏的name就是文件名,
                     * 文件名和之前的重複就會導致文件被覆蓋
                     */
                    ZipEntry zipEntry = new ZipEntry(name.get(i));//在壓縮目錄中文件的名字
                    zipStream.putNextEntry(zipEntry);//定位該壓縮條目位置,開始寫入文件到壓縮包中
                    bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
                    int read = 0;
                    byte[] buf = new byte[1024 * 10];
                    while((read = bufferStream.read(buf, 0, 1024 * 10)) != -1)
                    {
                        zipStream.write(buf, 0, read);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //關閉流
            try {
                if(null != bufferStream) {
                    bufferStream.close();
                }

                if(null != zipStream){
                    zipStream.flush();
                    zipStream.close();
                }
                if(null != zipSource){
                    zipSource.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //判斷當前壓縮文件是否生成存在:true-把該壓縮文件通過流輸出給客戶端後刪除該壓縮文件
        if(zipFile.exists()){
            //發送給客戶端
            fileUtils.downImgClient(response,zipFileName,strZipPath);
            //刪除本地存儲的文件
            zipFile.delete();
        }

    }
    //獲取excel表頭
     private String[] getFormFile(List<ProjectResult> projectResult, List<List<String>> lists) {
        for (ProjectResult item : projectResult) {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm");
            List<String> tem = new ArrayList<String>();
            //第一份
            tem.add(item.getProjectInfo().getDeptName());
            tem.add(item.getProjectInfo().getGroupNum());
            tem.add(item.getProjectInfo().getGroupName());
            tem.add(item.getProjectInfo().getCustManager());
            tem.add(item.getProjectInfo().getTmtType());
            tem.add(item.getProjectInfo().getProjectScene());
            tem.add(item.getProjectInfo().getProjectName());
            tem.add(item.getProjectInfo().getPlatformType());
            tem.add(item.getProjectInfo().getPackageSystem());
            tem.add(item.getProjectInfo().getPackageAll());
            //第二份
            tem.add(format.format(item.getProjectCpu().getAgreementDate()));
            tem.add(item.getProjectCpu().getProjectDiscount()+"%");
            tem.add(item.getProjectCpu().getProof());
            tem.add(item.getProjectCpu().getLead());
            tem.add(format.format(item.getProjectCpu().getValidDate()));
            tem.add(format.format(item.getProjectCpu().getValidEndDate()));
            tem.add(item.getProjectCpu().getMarketingNum());
            tem.add(item.getProjectCpu().getMarkejobNum());
            tem.add(item.getProjectCpu().getDiscountsWay());
            tem.add(item.getProjectCpu().getSystemDiscount()+"%");
            tem.add(item.getProjectCpu().getBackMoneyRatio()+"%");
            tem.add(Integer.toString(item.getProjectCpu().getSaleOpenNum()));
            tem.add(item.getProjectCpu().getSignFileName());
            tem.add(item.getProjectCpu().getMarketingFileName());
            //第三份
            tem.add(format.format(item.getProjectUser().getOpenDate()));
            tem.add(Integer.toString(item.getProjectUser().getOpenNum()));
            tem.add(item.getProjectUser().getOpenName());
            tem.add(item.getProjectUser().getAgreementIpv());
            tem.add(item.getProjectUser().getHandlingFormIpv());
            tem.add(item.getProjectUser().getApn());
            tem.add(item.getProjectUser().getApnName());
            tem.add(Integer.toString(item.getProjectUser().getOpenAll()));
            tem.add(item.getProjectUser().getAgreementFileName());
            tem.add(item.getProjectUser().getHandlingFileName());
            tem.add(item.getProjectUser().getBusinessFileName());
            tem.add(item.getProjectUser().getAutFileName());
            tem.add(item.getProjectUser().getCardFileName());
            tem.add(item.getProjectUser().getPortraitFileName());
            tem.add(item.getProjectUser().getNumberFileName());
            lists.add(tem);
        }
        return new String[]{"歸屬", "集團編號", "集團名稱", "客戶經理", "行業類型", "項目場景", "項目名稱", "卡平臺類型",
                "套餐資費體系", "套餐名稱+套餐程控資費", "客戶協議簽訂時間", "項目簽約折扣", "簽報文號", "簽報審批領導",
                "簽報有效起始時間","簽報有效終止時間", "營銷案編號","營銷活動編號", "優惠實現方式", "系統折扣", "饋贈金返充比例",
                "優惠開戶數", "簽報文件上傳", "營銷案上傳","開戶時間", "本次開戶數量", "開戶戶名", "協議版本", "受理單版本",
                "是否APN", "APN名稱", "累計開戶量", "協議上傳", "受理單上傳",
                "營業執照上傳", "授權書上傳", "經辦人身份證正反面上傳", "人像採集上傳", "號碼清單上傳"};
    }
發佈了13 篇原創文章 · 獲贊 2 · 訪問量 2469
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章