EasyExcel实现三级联动

前言

项目中需要在导出的模板中新增三级联动的功能,类似省市区的联动。在网上找了一些方法,都不能直接使用,需要进行修改。本文主要分享一下,改后的代码,可以直接使用。

代码

public class CascadeWriteHandler implements SheetWriteHandler {


    private static char[] alphabet = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
            'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

    //省
    private List<String> provinceList;
    //市
     Map<String, List<String>> cityMap;
    //区
    Map<String, List<String>> areaMap;

    //省列位置
    private int provinceIndex;
    //市列位置
    private intcityIndex;
    //区列位置
    private int areaIndex;


    public CascadeWriteHandler(List<String> provinceList, Map<String, List<String>> cityMap, Map<String, List<String>> areaMap, int provinceIndex, int intcityIndex, int areaIndex) {
        this.provinceList= provinceList;
        this.cityMap= cityMap;
        this.areaMap= areaMap;
        this.provinceIndex= provinceIndex;
        this.intcityIndex= intcityIndex;
        this.areaIndex= areaIndex;
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        //获取工作簿
        Sheet sheet = writeSheetHolder.getSheet();
        Workbook book = writeWorkbookHolder.getWorkbook();
        //创建一个专门用来存放地区信息的隐藏sheet页
        //因此不能在现实页之前创建,否则无法隐藏。
        Sheet hideSheet = book.createSheet("site");
        book.setSheetHidden(book.getSheetIndex(hideSheet), true);
        // 将具体的数据写入到每一行中,行开头为父级区域,后面是子区域。
        int rowId = 0;
        Row proviRow = hideSheet.createRow(rowId++);
        proviRow.createCell(0).setCellValue("大类列表");
        for (int i = 0; i < provinceIndex.size(); i++) {
            Cell proviCell = proviRow.createCell(i + 1);
            proviCell.setCellValue(provinceIndex.get(i));
        }
        Iterator<String> keyIterator = cityMap.keySet().iterator();
        while (keyIterator.hasNext()) {
            String key = keyIterator.next();
            List<String> son = cityMap.get(key);
            Row row = hideSheet.createRow(rowId++);
            for (int i = 0; i < son.size(); i++) {
                Cell cell = row.createCell(i + 1);
                cell.setCellValue(son.get(i));
            }
            // 添加名称管理器
            String range = getRange(1, rowId, son.size());
            Name name = book.createName();
            name.setNameName(key);
            String formula = "site!" + range;
            name.setRefersToFormula(formula);
        }
        Iterator<String> keyIterator1 = areaMap.keySet().iterator();
        while (keyIterator1.hasNext()) {
            String key = keyIterator1.next();
            List<String> son = areaMap.get(key);
            Row row = hideSheet.createRow(rowId++);
            for (int i = 0; i < son.size(); i++) {
                Cell cell = row.createCell(i + 1);
                cell.setCellValue(son.get(i));
            }
            // 添加名称管理器
            String range = getRange(1, rowId, son.size());
            Name name = book.createName();
            name.setNameName(key);
            String formula = "site!" + range;
            name.setRefersToFormula(formula);
        }

        ///开始设置(大类小类)下拉框
        DataValidationHelper dvHelper = sheet.getDataValidationHelper();
        // 大类规则
        DataValidationConstraint expConstraint = dvHelper.createExplicitListConstraint(industryList.toArray(new String[]{}));
        CellRangeAddressList expRangeAddressList = new CellRangeAddressList(1, 999, provinceIndex, provinceIndex);//todo 调整模板后位置需同步修改firstCol
        setValidation(sheet, dvHelper, expConstraint, expRangeAddressList, "提示", "你输入的值未在备选列表中,请下拉选择合适的值");

        // 小类规则(各单元格按个设置)
        // "INDIRECT($A$" + 2 + ")" 表示规则数据会从名称管理器中获取key与单元格 A2 值相同的数据,如果A2是浙江省,那么此处就是浙江省下面的市
        // 为了让每个单元格的公式能动态适应,使用循环挨个给公式。
        // 循环几次,就有几个单元格生效,次数要和上面的大类影响行数一一对应,要不然最后几个没对上的单元格实现不了级联
        for (int i = 2; i < 1000; i++) {
            CellRangeAddressList rangeAddressList = new CellRangeAddressList(i - 1, i - 1, intcityIndex, intcityIndex);//todo 调整模板后位置需同步修改firstCol
            DataValidationConstraint formula = dvHelper.createFormulaListConstraint("INDIRECT($"+getExcelColumn(intcityIndex-1)+"$" + i + ")");//todo 调整模板后位置需同步修改字母
            setValidation(sheet, dvHelper, formula, rangeAddressList, "提示", "你输入的值未在备选列表中,请下拉选择合适的值");
        }

        for (int i = 2; i < 1000; i++) {
            CellRangeAddressList rangeAddressList = new CellRangeAddressList(i - 1, i - 1, areaIndex, areaIndex);//todo 调整模板后位置需同步修改firstCol
            DataValidationConstraint formula = dvHelper.createFormulaListConstraint("INDIRECT($"+getExcelColumn(areaIndex-1)+"$" + i + ")");//todo 调整模板后位置需同步修改字母
            setValidation(sheet, dvHelper, formula, rangeAddressList, "提示", "你输入的值未在备选列表中,请下拉选择合适的值");
        }
    }

    /**
     * 设置验证规则
     *
     * @param sheet       sheet对象
     * @param helper      验证助手
     * @param constraint  createExplicitListConstraint
     * @param addressList 验证位置对象
     * @param msgHead     错误提示头
     * @param msgContext  错误提示内容
     */
    private void setValidation(Sheet sheet, DataValidationHelper helper, DataValidationConstraint constraint, CellRangeAddressList addressList, String msgHead, String msgContext) {
        DataValidation dataValidation = helper.createValidation(constraint, addressList);
        dataValidation.setErrorStyle(DataValidation.ErrorStyle.STOP);
        dataValidation.setShowErrorBox(true);
        dataValidation.setSuppressDropDownArrow(true);
        dataValidation.createErrorBox(msgHead, msgContext);
        sheet.addValidationData(dataValidation);
    }

    /**
     * @param offset   偏移量,如果给0,表示从A列开始,1,就是从B列
     * @param rowId    第几行
     * @param colCount 一共多少列
     * @return 如果给入参 1,1,10. 表示从B1-K1。最终返回 $B$1:$K$1
     * @author denggonghai 2016年8月31日 下午5:17:49
     */
    public String getRange(int offset, int rowId, int colCount) {
        char start = (char) ('A' + offset);
        if (colCount <= 25) {
            char end = (char) (start + colCount - 1);
            return "$" + start + "$" + rowId + ":$" + end + "$" + rowId;
        } else {
            char endPrefix = 'A';
            char endSuffix = 'A';
            if ((colCount - 25) / 26 == 0 || colCount == 51) {// 26-51之间,包括边界(仅两次字母表计算)
                if ((colCount - 25) % 26 == 0) {// 边界值
                    endSuffix = (char) ('A' + 25);
                } else {
                    endSuffix = (char) ('A' + (colCount - 25) % 26 - 1);
                }
            } else {// 51以上
                if ((colCount - 25) % 26 == 0) {
                    endSuffix = (char) ('A' + 25);
                    endPrefix = (char) (endPrefix + (colCount - 25) / 26 - 1);
                } else {
                    endSuffix = (char) ('A' + (colCount - 25) % 26 - 1);
                    endPrefix = (char) (endPrefix + (colCount - 25) / 26);
                }
            }
            return "$" + start + "$" + rowId + ":$" + endPrefix + endSuffix + "$" + rowId;
        }
    }

    /**
     * 将数字列转化成为字母列
     *
     * @param num
     * @author: Jesse
     * @date: 2023/6/27
     * @return: String
     */
    private static String getExcelColumn(int num) {
        String column = "";
        int len = alphabet.length - 1;
        int first = num / len;
        int second = num % len;
        if (num <= len) {
            column = alphabet[num] + "";
        } else {
            column = alphabet[first - 1] + "";
            if (second == 0) {
                column = column + alphabet[len] + "";
            } else {
                column = column + alphabet[second - 1] + "";
            }
        }
        return column;
    }

}

ExcelProjectDto 类

@ColumnWidth(22)
@HeadRowHeight(30)
public class ExcelProjectDto {

    /**
     * 项目名称
     */
    @ExcelProperty(value = "项目名称")//表头注解
    private String projName;

    /**
     * 项目所在企业名称
     */
    @ExcelProperty(value = "企业名称")
    private String enterpriseName;

    /**
     * 项目所在地级名称
     */
    @ExcelProperty(value = "地市")
    private String area20Name;

    /**
     * 项目所在县级名称
     */
    @ExcelProperty(value = "区县")
    private String area30Name;

    public String getProjName() {
        return projName;
    }

    public void setProjName(String projName) {
        this.projName = projName;
    }

    public String getEnterpriseName() {
        return enterpriseName;
    }

    public void setEnterpriseName(String enterpriseName) {
        this.enterpriseName = enterpriseName;
    }

    public String getArea20Name() {
        return area20Name;
    }

    public void setArea20Name(String area20Name) {
        this.area20Name = area20Name;
    }

    public String getArea30Name() {
        return area30Name;
    }

    public void setArea30Name(String area30Name) {
        this.area30Name = area30Name;
    }

    public ExcelProjectDto(String projName, String enterpriseName, String area20Name, String area30Name) {
        this.projName = projName;
        this.enterpriseName = enterpriseName;
        this.area20Name = area20Name;
        this.area30Name = area30Name;
    }

    public ExcelProjectDto() {
    }
}

测试

public class EasyExcelTest {

    public static void main(String[] args) {
        List<ExcelProjectDto> dataList = new ArrayList<>();

        /// 准备省市aqu测试数据
        List<String> provinceList = Arrays.asList("apro1", "apro2", "apro3");

        Map<String, List<String>> cityMap = new HashMap<>();
        cityMap.put("apro1", Arrays.asList("acity11", "acity12"));
        cityMap.put("apro2", Arrays.asList("acity21", "acity22"));
        cityMap.put("apro3", Arrays.asList("acity31", "acity32"));

        Map<String, List<String>> districtMap = new HashMap<>();
        districtMap.put("acity11", Arrays.asList("aqu111", "aqu112"));
        districtMap.put("acity12", Arrays.asList("aqu121", "aqu122"));
        districtMap.put("acity21", Arrays.asList("aqu211", "aq212"));
        districtMap.put("acity22", Arrays.asList("aqu221", "aqu222"));
        districtMap.put("acity31", Arrays.asList("aqu311", "aqu312"));
        districtMap.put("acity32", Arrays.asList("aqu321", "aqu322"));

        // 创建写入的Sheet
        File file = new File("D:\\data\\test.xlsx");
        EasyExcel.write(file)
                .sheet("sheet1").head(ExcelProjectDto.class)
                .registerWriteHandler(new CascadeWriteHandler11(provinceList, cityMap,districtMap,4,5,6)).
                doWrite(dataList);

    }
}

总结

以上就是excel实现三级联动的功能实现。当然如果你觉得这么写非常麻烦,也可以将设置好的excel,上传到指定目录下,通过直接下载excel的形式实现该功能。以上就是本次分享的内容,如有不足请多多指正。

你可能感兴趣的:(windows,excel)