代碼優化 - 上

       最近在寫Excel導出功能,需要合併多行,優化過程分爲了上下兩篇,上篇是基礎篇,下篇是優化篇,優化是利用java8 提供的新功能,方法可以作爲參數傳遞!

 

這是導出的Excel的樣式

   

優化的內容,僅涉及下面單元格內容數據填充,下面的幾個方法。

待優化方法,結構基本相似,當currRow < maxRow的時候,是需要合併單元格的,否則不需要合併,所以每個方法就分了需要合併單元格和不需要合併單元格兩種情況去考慮。頭部的一段是判斷實體或者數組是否爲空,爲空的話,設置單元格的值爲""(默認值)。待優化的方法分爲兩類,一類是往Excel中寫單行,參數傳的是Entity,一類是往Excel中寫多行,參數傳的是List。單行的情況

多行的情況:

 

下面是具體代碼,可以瀏覽一下。代碼單獨跑是跑不起來的,但是可以觀思路


    private void writeToResponse(ContestEnterpriseExportReqForm reqForm, List<ContestEnterpriseListResultBean> enterpriseList, Map<Long, String> fieldMap) {
        HttpServletResponse response = reqForm.getServletResponse();

        List<ExcelHeader> headerList = initExcelHeaderList();
        KrExcelWriteBuilder builder = KrExcelWriteBuilder.build()
                .setSheetName("企業用戶")
                .setMaxRowNumPerSheet(1000)
                .setHeaderRowNum(1)
                .setHeaderList(headerList)
                .setDataRowNum(2);

        String dateNow = DateUtil.formatByPattern(Instant.now().toEpochMilli(), DateUtil.DATE_FORMAT);
        String fileName = dateNow + "_" + UUIDUtil.getUUID() + ".xlsx";

        KrExcelWrite write = new DefaultExcelWriteImpl();
        try {
            initResponseHeader(response, fileName);
            write.exportMergedRegion(response.getOutputStream(), builder, new KrExcelWriteDataSource(enterpriseList, fieldMap));
        } catch (IOException e) {
            logger.error("下載文件時候發生異常:{}", ExceptionUtil.outException(e));
        }
    }

    private List<ExcelHeader> initExcelHeaderList() {
        int width = 5000;
        List<ExcelHeader> headerList = new ArrayList<>();
        addExcelColHeader(headerList, "ID", "id", 2000);
        addExcelColHeader(headerList, "公司名稱", "name", width);
        addExcelColHeader(headerList, "一句話介紹", "oneWordBrief", width);
        addExcelColHeader(headerList, "企業簡介", "brief", width);
        addExcelColHeader(headerList, "成立時間", "createData", width);
        addExcelColHeader(headerList, "公司官網", "website", width);
        addExcelColHeader(headerList, "融資輪次", "lastFinanceRound", width);
        addExcelColHeader(headerList, "公司規模", "scale", width);
        addExcelColHeader(headerList, "所在地", "address", width);
        addExcelColHeader(headerList, "註冊地", "registAddress", width);
        addExcelColHeader(headerList, "所在領域", "field", width);
        addExcelColHeader(headerList, "融資-序號", "financeNo", width);
        addExcelColHeader(headerList, "融資-金額", "financeMoney", width);
        addExcelColHeader(headerList, "融資-輪次", "financeRound", width);
        addExcelColHeader(headerList, "融資-投資方", "financeInvestor", width);
        addExcelColHeader(headerList, "核心成員-序號", "coreMemberNo", width);
        addExcelColHeader(headerList, "核心成員-姓名", "coreMemberName", width);
        addExcelColHeader(headerList, "核心成員-職位", "coreMemberPosition", width);
        addExcelColHeader(headerList, "核心成員-簡介", "coreMemberBrief", width);
        addExcelColHeader(headerList, "聯繫人-姓名", "contactName", width);
        addExcelColHeader(headerList, "聯繫人-手機號", "contactMobile", width);
        addExcelColHeader(headerList, "聯繫人-郵箱", "contactEmail", width);
        addExcelColHeader(headerList, "聯繫人-職位", "contactPosition", width);
        addExcelColHeader(headerList, "BP", "BP", width);
        addExcelColHeader(headerList, "往期報名-報名時間", "pastApplyDate", width);
        addExcelColHeader(headerList, "往期報名-招募活動名稱", "pastApplyActivity", width);
        addExcelColHeader(headerList, "往期報名-方案", "pastApplyPlan", width);
        addExcelColHeader(headerList, "往期報名-入圍情況", "pastApplyShortlisted", width);
        return headerList;
    }

    private void addExcelColHeader(List<ExcelHeader> headerList, String columnName, String property, int width) {
        ExcelHeader header = new ExcelHeader();
        header.setColumnName(columnName);
        header.setColumnProperty(property);
        header.setWidth(width);
        headerList.add(header);
    }

    private void initResponseHeader(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        response.setContentType("application/octet-stream");
        //設置Http響應頭告訴瀏覽器下載這個附件
        response.setHeader("Content-disposition", "attachment; filename="
                + fileName);
//        response.setHeader("Content-Length", response.getOutputStream());
//        response.setContentType("application/json;charset=utf-8");
    }

    private class KrExcelWriteDataSource implements com.kr.media.util.doc.excel.KrExcelWriteDataSource {
        private List<ContestEnterpriseListResultBean> enterpriseList;
        private Map<Long, String> fieldMap;

        private final int pageSize = 1000;

        private volatile int curPage = 0;
        private final int totalPage;
        private final int totalCount;

        private int currRow = 1;
        private int total = 0;

        public KrExcelWriteDataSource(List<ContestEnterpriseListResultBean> enterpriseList, Map<Long, String> fieldMap) {
            this.enterpriseList = enterpriseList;
            this.fieldMap = fieldMap;

            this.totalCount = enterpriseList == null ? 0 : enterpriseList.size();
            this.totalPage = totalCount / pageSize + 1;
        }

        @Override
        public boolean hasNext() {
            curPage++;
            if (curPage <= totalPage) {
                return true;
            }
            return false;
        }

        @Override
        public List<ExcelRow> next() {
            List<ExcelRow> rowList = new ArrayList<>();
            if (enterpriseList == null || enterpriseList.isEmpty()) {
                ExcelRow excelRow = new ExcelRow();
                excelRow.setObject("id", "空");
                rowList.add(excelRow);
                return rowList;
            }

            int startIndex = (curPage - 1) * pageSize;
            if (startIndex > totalCount) {
                return rowList;
            }

            int endIndex = curPage * pageSize - 1;
            if (endIndex > (totalCount - 1)) {
                endIndex = totalCount - 1;
            }
            Map<Long, String> userCityMap = getUserCityMap(enterpriseList);

            logger.info("導出企業用戶信息{}條", enterpriseList.size());

            for (int i = startIndex; i <= endIndex; i++) {
                ContestEnterpriseListResultBean enterprise = enterpriseList.get(i);
                long enterpriseId = enterprise.getId();

                int dataMaxSize = 0;
                // 融資情況
                List<ContestEnterpriseFinanceHistory> financeHistories = contestEnterpriseFinanceHistoryService.findByEnterpriseId(enterpriseId);
                if (dataMaxSize < financeHistories.size()) {
                    dataMaxSize = financeHistories.size();
                }

                // 核心成員
                List<ContestEnterpriseMember> memberList = contestEnterpriseMemberService.findByEnterpriseId(enterpriseId);
                if (dataMaxSize < memberList.size()) {
                    dataMaxSize = memberList.size();
                }

                // 往期報名
                List<ContestSignup> contestSignupList = contestSignupService.findByEnterpriseId(enterpriseId);
                if (dataMaxSize < contestSignupList.size()) {
                    dataMaxSize = contestSignupList.size();
                }

                int maxRow = currRow;
                if (dataMaxSize > 1) {
                    maxRow = currRow + dataMaxSize - 1;
                }

                if (total % pageSize == 0) {
                    currRow = 1;
                }


                ExcelRow row = new ExcelRow();
                rowList.add(row);

                row.setStartRow(currRow);
                row.setEndRow(maxRow);

                List<ExcelRow.MergedRegion> mergedRegionList = new ArrayList<>();
                row.setMergedRegionList(mergedRegionList);

                int colIndex = 0;



//優化的內容,僅涉及下面單元格內容數據填充,下面的幾個方法,結構基本相似,當currRow < maxRow的時候,是需要合併單元格的,否則不需要合併,所以每個方法就分了需要合併單元格和不需要合併單元格兩種情況去考慮。頭部的一段是判斷實體或者數組是否爲空,爲空的話,設置單元格的值爲""(默認值)。

                // 企業基本信息
                ContestEnterpriseTianyancha enterpriseTianyancha = contestEnterpriseTianyanchaService.findByEnterpriseId(enterpriseId);
                colIndex = setEnterpriseBaseInfo(row, currRow, colIndex, enterprise, enterpriseTianyancha, fieldMap, maxRow, mergedRegionList);

                // 融資情況
                colIndex = setFinanceMessageList(row, currRow, colIndex, financeHistories, maxRow, mergedRegionList);

                // 核心成員
                colIndex = setMemberList(row, currRow, colIndex, memberList, maxRow, mergedRegionList);

                // 聯繫人
                ContestEnterprise contestEnterprise = contestEnterpriseService.get(enterpriseId);
                colIndex = setContactBean(row, currRow, colIndex, contestEnterprise, maxRow, mergedRegionList);

                // BP
                colIndex = setBP(row, currRow, colIndex, contestEnterprise, maxRow, mergedRegionList);


                // 往期報名
                colIndex = setHistoryContestSignupList(row, currRow, colIndex, contestSignupList, maxRow, mergedRegionList);

                currRow = maxRow + 1;
                total++;
            }
            return rowList;
        }
    }

    private Map<Long, String> getUserCityMap(List<ContestEnterpriseListResultBean> userList) {
        List<Long> cityIdList = userList.stream().map(ContestEnterpriseListResultBean::getCityId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(cityIdList)) {
            return Collections.emptyMap();
        }

        ResDataBean<CityBatchBean> resDataBean = ClientServiceFactory.getInstance().getCityService().findCityById(cityIdList);
        if (resDataBean == null || resDataBean.getData() == null || resDataBean.getData().getCityList() == null) {
            return Collections.emptyMap();
        }

        List<CityBatchBean.CityBean> cityList = resDataBean.getData().getCityList();

        return cityList.stream().collect(Collectors.toMap(CityBatchBean.CityBean::getId, CityBatchBean.CityBean::getName));
    }

    /**
     * 企業基本信息
     *
     * @param row
     * @param currRow
     * @param colIndex
     * @param entity
     * @param fieldMap
     * @return
     */
    private int setEnterpriseBaseInfo(ExcelRow row, int currRow, int colIndex, ContestEnterpriseListResultBean entity, ContestEnterpriseTianyancha enterpriseTianyancha, Map<Long, String> fieldMap, int maxRow, List<ExcelRow.MergedRegion> mergedRegionList) {
        String id = "", name = "", briefIntro = "", intro = "", setUpTime = "", website = "",
                financingRound = "", companySize = "", address = "", registAddress = "", field = "";
        if (entity != null) {
            id = String.valueOf(entity.getId());
            name = entity.getEnterpriseTitle();
            briefIntro = entity.getBriefIntro();
        }

        if (enterpriseTianyancha != null) {
            intro = enterpriseTianyancha.getIntro();
            if(enterpriseTianyancha.getSetUpTime() != null){
                setUpTime = DateUtil.formatByPattern(enterpriseTianyancha.getSetUpTime(), DateUtil.DATE_FORMAT);
            }
            website = enterpriseTianyancha.getWebsite();
            financingRound = enterpriseTianyancha.getFinanceRound();
            companySize = enterpriseTianyancha.getCompanySize();
            address = enterpriseTianyancha.getAddress();
            registAddress = enterpriseTianyancha.getRegisteredAddress();
            field = getFieldStr(entity.getId(), fieldMap);
        }

        if(currRow < maxRow){
            //需要合併
            return setBaseInfoWithMerge(row, currRow, colIndex, maxRow, mergedRegionList, id, name, briefIntro, intro, setUpTime, website, financingRound, companySize, address, registAddress, field);
        }else {
            return setBaseInfoWithOutMerge(row, currRow, colIndex,  id, name, briefIntro, intro, setUpTime, website, financingRound, companySize, address, registAddress, field);
        }
    }

    private int setBaseInfoWithMerge(ExcelRow row, int currRow, int colIndex, int maxRow, List<ExcelRow.MergedRegion> mergedRegionList,
                String id, String name, String briefIntro, String intro, String setUpTime, String website,
                String financingRound, String companySize, String address, String registAddress, String field) {
        // id
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), id);

        //公司名稱
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), name);

        //一句話介紹
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), briefIntro);

        //企業簡介
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), intro);
        //成立時間
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), setUpTime);
        //公司官網
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        if(StringUtils.isNotBlank(website)){
            website = OspsUtil.formatUrl(website, Arrays.asList(formatUrl.split(",")));
            row.setObject(currRow + "-" + (colIndex++), KrExcelWrite.WriteType.FORMULA_URL, "HYPERLINK(\"" + website + "\",\"" + website + "\")");
        }else{
            row.setObject(currRow + "-" + (colIndex++), website);
        }
        //融資輪次
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), financingRound);
        //公司規模
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), companySize);

        //所在地
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), address);
        //註冊地
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), registAddress);
        //所在領域
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), field);
        return colIndex;
    }

    private int setBaseInfoWithOutMerge(ExcelRow row, int currRow, int colIndex, String id, String name,
                  String briefIntro, String intro, String setUpTime, String website, String financingRound,
                  String companySize, String address, String registAddress, String field) {
        // id
        row.setObject(currRow + "-" + (colIndex++), id);

        //公司名稱
        row.setObject(currRow + "-" + (colIndex++), name);

        //一句話介紹
        row.setObject(currRow + "-" + (colIndex++), briefIntro);

        //企業簡介
        row.setObject(currRow + "-" + (colIndex++), intro);
        //成立時間
        row.setObject(currRow + "-" + (colIndex++), setUpTime);
        //公司官網
        if(StringUtils.isNotBlank(website)){
            website = OspsUtil.formatUrl(website, Arrays.asList(formatUrl.split(",")));
            row.setObject(currRow + "-" + (colIndex++), KrExcelWrite.WriteType.FORMULA_URL, "HYPERLINK(\"" + website + "\",\"" + website + "\")");
        }else{
            row.setObject(currRow + "-" + (colIndex++), website);
        }
        //融資輪次
        row.setObject(currRow + "-" + (colIndex++), financingRound);
        //公司規模
        row.setObject(currRow + "-" + (colIndex++), companySize);

        //所在地
        row.setObject(currRow + "-" + (colIndex++), address);
        //註冊地
        row.setObject(currRow + "-" + (colIndex++), registAddress);
        //所在領域
        row.setObject(currRow + "-" + (colIndex++), field);
        return colIndex;
    }

    private int setFinanceMessageList(ExcelRow row, int currRow, int colIndex, List<ContestEnterpriseFinanceHistory> financeHistories, int maxRow, List<ExcelRow.MergedRegion> mergedRegionList) {

        if (CollectionUtils.isEmpty(financeHistories)) {
            if (currRow < maxRow) {
                //需要合併行
                //融資-序號
                mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
                row.setObject(currRow + "-" + (colIndex++), "");
                //融資-金額
                mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
                row.setObject(currRow + "-" + (colIndex++), "");
                //融資-輪次
                mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
                row.setObject(currRow + "-" + (colIndex++), "");
                //融資-投資方
                mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
                row.setObject(currRow + "-" + (colIndex++), "");
            } else {
                //融資-序號
                row.setObject(currRow + "-" + (colIndex++), "");
                //融資-金額
                row.setObject(currRow + "-" + (colIndex++), "");
                //融資-輪次
                row.setObject(currRow + "-" + (colIndex++), "");
                //融資-投資方
                row.setObject(currRow + "-" + (colIndex++), "");
            }
            return colIndex;
        }
        int dataSize = financeHistories.size();
        for (int index = 0; index < dataSize; index++) {
            int currColIndex = colIndex;
            ContestEnterpriseFinanceHistory finance = financeHistories.get(index);

            if (dataSize > 1 && index == dataSize - 1 && currRow < maxRow) {
                //最後一行需要合併行
                //融資-序號
                mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, currColIndex, currColIndex));
                row.setObject(currRow + "-" + (currColIndex++), String.valueOf(index + 1));

                //融資-金額
                mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, currColIndex, currColIndex));
                row.setObject(currRow + "-" + (currColIndex++), finance.getMoney());

                //融資-輪次
                mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, currColIndex, currColIndex));
                row.setObject(currRow + "-" + (currColIndex++), finance.getRound());

                //融資-投資方
                mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, currColIndex, currColIndex));
                row.setObject(currRow + "-" + (currColIndex++), finance.getInvestorName());

            } else {
                //融資-序號
                row.setObject(currRow + "-" + (currColIndex++), String.valueOf(index + 1));

                //融資-金額
                row.setObject(currRow + "-" + (currColIndex++), finance.getMoney());

                //融資-輪次
                row.setObject(currRow + "-" + (currColIndex++), finance.getRound());

                //融資-投資方
                row.setObject(currRow + "-" + (currColIndex++), finance.getInvestorName());
            }
            currRow++;
        }
        return colIndex + 4;
    }

    private int setFinanceWithMerge(ExcelRow row, int currRow, int colIndex, List<ContestEnterpriseFinanceHistory> financeHistories, int maxRow, List<ExcelRow.MergedRegion> mergedRegionList, String no, String money, String round, String investor) {
        //需要合併行
        //融資-序號
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), no);
        //融資-金額
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), money);
        //融資-輪次
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), round);
        //融資-投資方
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), investor);
        return colIndex;
    }

    private int setFinanceWithOutMerge(ExcelRow row, int currRow, int colIndex, String no, String money, String round, String investor) {
        //融資-序號
        row.setObject(currRow + "-" + (colIndex++), no);
        //融資-金額
        row.setObject(currRow + "-" + (colIndex++), money);
        //融資-輪次
        row.setObject(currRow + "-" + (colIndex++), round);
        //融資-投資方
        row.setObject(currRow + "-" + (colIndex++), investor);
        return colIndex;
    }

    private int setMemberList(ExcelRow row, int currRow, int colIndex, List<ContestEnterpriseMember> memberList, int maxRow, List<ExcelRow.MergedRegion> mergedRegionList) {
        String no = "", name = "", position = "", desc = "";
        if (CollectionUtils.isEmpty(memberList)) {
            if (currRow < maxRow) {
                // 需要合併行
                return setMemberWithMerge(row, currRow, colIndex, maxRow, mergedRegionList, no, name, position, desc);
            } else {
                return setMemberWithOutMerge(row, currRow, colIndex, no, name, position, desc);
            }
        }

        int dataSize = memberList.size();
        for (int index = 0; index < dataSize; index++) {
            ContestEnterpriseMember member = memberList.get(index);

            no = String.valueOf(index + 1);
            name = member.getName();
            position = member.getTitle();
            desc = member.getDesc();

            if (dataSize > 1 && index == dataSize - 1 && currRow < maxRow) {
                //最後一行需要合併行
                setMemberWithMerge(row, currRow, colIndex, maxRow, mergedRegionList, no, name, position, desc);
            } else {
                setMemberWithOutMerge(row, currRow, colIndex, no, name, position, desc);
            }

            currRow++;
        }
        return colIndex + 4;
    }



    private int setMemberWithMerge(ExcelRow row, int currRow, int colIndex, int maxRow, List<ExcelRow.MergedRegion> mergedRegionList, String no, String name, String position, String desc) {
        //需要合併行
        //核心成員-序號
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), no);
        //核心成員-姓名
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), name);
        //核心成員-職位
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), position);
        //核心成員-簡介
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), desc);
        return colIndex;
    }

    private int setMemberWithOutMerge(ExcelRow row, int currRow, int colIndex, String no, String name, String position, String desc) {
        //核心成員-序號
        row.setObject(currRow + "-" + (colIndex++), no);
        //核心成員-姓名
        row.setObject(currRow + "-" + (colIndex++), name);
        //核心成員-職位
        row.setObject(currRow + "-" + (colIndex++), position);
        //核心成員-簡介
        row.setObject(currRow + "-" + (colIndex++), desc);
        return colIndex;
    }

    private int setContactBean(ExcelRow row, int currRow, int colIndex, ContestEnterprise entity, int maxRow, List<ExcelRow.MergedRegion> mergedRegionList) {
        String name = "", mobileNo = "", email = "", position = "";
        if (entity != null) {
            name = entity.getContactsName();
            mobileNo = entity.getContactsMobileNo() == null ? null : entity.getContactsMobileNo().toString();
            email = entity.getContactsMobileEmail();
            position = entity.getContactsPosition();
        }

        if(currRow < maxRow){
            //需要合併
            return setContactBeanWithMerge(row, currRow, colIndex, maxRow, mergedRegionList, name, mobileNo, email, position);
        }else {
            return setContactBeanWithoutMerge(row, currRow, colIndex, name, mobileNo, email, position);
        }
    }

    private int setContactBeanWithMerge(ExcelRow row, int currRow, int colIndex, int maxRow, List<ExcelRow.MergedRegion> mergedRegionList, String name, String mobileNo, String email, String position) {
        // 聯繫人-姓名
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), name);

        // 聯繫人-手機號
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), mobileNo);

        // 聯繫人-郵箱
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), email);

        // 聯繫人-職位
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), position);
        return colIndex;
    }

    private int setContactBeanWithoutMerge(ExcelRow row, int currRow, int colIndex, String name, String mobileNo, String email, String position) {
        // 聯繫人-姓名
        row.setObject(currRow + "-" + (colIndex++), name);

        // 聯繫人-手機號
        row.setObject(currRow + "-" + (colIndex++), mobileNo);

        // 聯繫人-郵箱
        row.setObject(currRow + "-" + (colIndex++), email);

        // 聯繫人-職位
        row.setObject(currRow + "-" + (colIndex++), position);
        return colIndex;
    }

    private int setBP(ExcelRow row, int currRow, int colIndex, ContestEnterprise entity, int maxRow, List<ExcelRow.MergedRegion> mergedRegionList) {
        String fileLink = "", fileName = "";
        if (entity != null) {
            fileLink = entity.getEnterpriseBpUrl();
            fileName = entity.getEnterpriseBpName();
        }

        if(currRow < maxRow){
            //需要合併
            return setBPWithMerge(row, currRow, colIndex, maxRow, mergedRegionList, fileLink, fileName);
        }else {
            return setBPWithoutMerge(row, currRow, colIndex, fileLink, fileName);
        }
    }

    private int setBPWithMerge(ExcelRow row, int currRow, int colIndex, int maxRow, List<ExcelRow.MergedRegion> mergedRegionList, String fileLink, String fileName) {
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        if (StringUtils.isNotBlank(fileLink) && StringUtils.isNotBlank(fileName)) {
            fileLink = OspsUtil.formatUrl(fileLink, Arrays.asList(formatUrl.split(",")));
            row.setObject(currRow + "-" + (colIndex++), KrExcelWrite.WriteType.FORMULA_URL, "HYPERLINK(\"" + fileLink + "\",\"" + fileName + "\")");
        } else {
            row.setObject(currRow + "-" + (colIndex++), "");
        }
        return colIndex;
    }

    private int setBPWithoutMerge(ExcelRow row, int currRow, int colIndex, String fileLink, String fileName) {
        if (StringUtils.isNotBlank(fileLink) && StringUtils.isNotBlank(fileName)) {
            fileLink = OspsUtil.formatUrl(fileLink, Arrays.asList(formatUrl.split(",")));
            row.setObject(currRow + "-" + (colIndex++), KrExcelWrite.WriteType.FORMULA_URL, "HYPERLINK(\"" + fileLink + "\",\"" + fileName + "\")");
        } else {
            row.setObject(currRow + "-" + (colIndex++), "");
        }
        return colIndex;
    }

    private int setHistoryContestSignupList(ExcelRow row, int currRow, int colIndex, List<ContestSignup> contestSignupList, int maxRow, List<ExcelRow.MergedRegion> mergedRegionList) {
        String applyTime = "", recruitTitle = "", fileName = "", fileUrl = "", evaluateStatus = "";
        if (CollectionUtils.isEmpty(contestSignupList)) {
            if (currRow < maxRow) {
                // 需要合併行
                return setHistoryContestSignupWithMerge(row, currRow, colIndex, maxRow, mergedRegionList, applyTime, recruitTitle, fileName, fileUrl, evaluateStatus);
            } else {
                return setHistoryContestSignupWithOutMerge(row, currRow, colIndex, applyTime, recruitTitle, fileName, fileUrl, evaluateStatus);
            }
        }

        int dataSize = contestSignupList.size();
        for (int index = 0; index < dataSize; index++) {
            int currColIndex = colIndex;
            ContestSignup signup = contestSignupList.get(index);

            //往期報名-報名時間
            applyTime = DateUtil.formatByPattern(signup.getCreateTime(), DateUtil.DATE_TIME_FORMAT_DEFAULT);

            //往期報名-招募活動名稱
            recruitTitle = "";
            ContestRecruit contestRecruit = contestRecruitService.get(signup.getRecrcuitId());
            if (contestRecruit != null) {
                recruitTitle = contestRecruit.getRecruitTitle();
            }

            //往期報名-方案
            fileName = signup.getOpusName();
            fileUrl = signup.getOpusUrl();

            //往期報名-入圍情況
            evaluateStatus = "";
            ContestSignupService.EvaluateStatusEnum evaluateEnum = EnumUtil.getByKey(ContestSignupService.EvaluateStatusEnum.class, ContestSignupService.EvaluateStatusEnum::getCode, signup.getEvaluateStatus());
            if (evaluateEnum != null) {
                evaluateStatus = evaluateEnum.getName();
            }

            if (dataSize > 1 && index == dataSize - 1 && currRow < maxRow) {
                //最後一行 && 沒有到達maxRow 需要合併行
                setHistoryContestSignupWithMerge(row, currRow, currColIndex, maxRow, mergedRegionList, applyTime, recruitTitle, fileName, fileUrl, evaluateStatus);
            } else {
                setHistoryContestSignupWithOutMerge(row, currRow, currColIndex, applyTime, recruitTitle, fileName, fileUrl, evaluateStatus);
            }
            currRow++;
        }
        return colIndex + 4;

    }

    private int setHistoryContestSignupWithMerge(ExcelRow row, int currRow, int colIndex, int maxRow, List<ExcelRow.MergedRegion> mergedRegionList, String applyTime, String recruitTitle, String fileName, String fileUrl, String evaluateStatus) {
        // 需要合併行
        //往期報名-報名時間
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), applyTime);
        //往期報名-招募活動名稱
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), recruitTitle);
        //往期報名-方案
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        if (StringUtils.isNotBlank(fileName) && StringUtils.isNotBlank(fileUrl)) {
            String fileLink = OspsUtil.formatUrl(fileUrl, Arrays.asList(formatUrl.split(",")));
            row.setObject(currRow + "-" + (colIndex++), KrExcelWrite.WriteType.FORMULA_URL, "HYPERLINK(\"" + fileLink + "\",\"" + fileName + "\")");
        } else {
            row.setObject(currRow + "-" + (colIndex++), "");
        }
        //往期報名-入圍情況
        mergedRegionList.add(new ExcelRow.MergedRegion(currRow, maxRow, colIndex, colIndex));
        row.setObject(currRow + "-" + (colIndex++), evaluateStatus);
        return colIndex;
    }

    private int setHistoryContestSignupWithOutMerge(ExcelRow row, int currRow, int colIndex, String applyTime, String recruitTitle, String fileName, String fileUrl, String evaluateStatus) {
        // 不需要合併行
        //往期報名-報名時間
        row.setObject(currRow + "-" + (colIndex++), applyTime);
        //往期報名-招募活動名稱
        row.setObject(currRow + "-" + (colIndex++), recruitTitle);
        //往期報名-方案
        if (StringUtils.isNotBlank(fileName) && StringUtils.isNotBlank(fileUrl)) {
            String fileLink = OspsUtil.formatUrl(fileUrl, Arrays.asList(formatUrl.split(",")));
            row.setObject(currRow + "-" + (colIndex++), KrExcelWrite.WriteType.FORMULA_URL, "HYPERLINK(\"" + fileLink + "\",\"" + fileName + "\")");
        } else {
            row.setObject(currRow + "-" + (colIndex++), "");
        }
        //往期報名-入圍情況
        row.setObject(currRow + "-" + (colIndex++), evaluateStatus);
        return colIndex;
    }

    private String getFieldStr(Long id, Map<Long, String> fieldMap) {

        List<ContestEnterpriseField> fieldList = contestEnterpriseFieldService.findByEnterpriseId(id);
        List<ContestEnterpriseSubField> subFieldList = contestEnterpriseSubFieldService.findByEnterpriseId(id);


        List<Long> fieldIdList = fieldList.stream().map(ContestEnterpriseField::getSubFieldType).collect(Collectors.toList());
        List<Long> subFieldIdList = subFieldList.stream().map(ContestEnterpriseSubField::getSubFieldType).collect(Collectors.toList());

        fieldIdList.addAll(subFieldIdList);

        List<String> list = new ArrayList<>();
        fieldIdList.forEach(fieldId -> {
            String field = fieldMap.get(fieldId);
            list.add(field);
        });

        if (CollectionUtils.isNotEmpty(list)) {
            return StringUtils.join(list, "、");
        }
        return null;
    }

參考:java poi 合併單元格

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章