代码优化 - 上

       最近在写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 合并单元格

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