EasyExcel导出Excel 自定义 表头颜色

目的1:自定义RGB 来自定义表头 导出 excel 的表头颜色
目的2:excel 下拉框数据验证

pom 依赖

 <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.7</version>
        </dependency>

相关示例代码
ExcelUtils 工具类中可以本地测试

/**
 * 表头 颜色 定义
 */
public class ComplexHeadStyles {
    /**
     * 表头横坐标 - 行
     */
    private Integer x;

    /**
     * 表头纵坐标 - 列
     */
    private Integer y;

    /**
     * 内置颜色
     */
    private Short indexColor;

    private Integer red;
    private Integer green;
    private Integer blue;

    /**
     * 字体颜色
     */
    private Short fontColor;

    public ComplexHeadStyles(Integer x, Integer y, Short indexColor) {
        this.x = x;
        this.y = y;
        this.indexColor = indexColor;
    }
    public ComplexHeadStyles(Integer x, Integer y, Integer red, Integer green, Integer blue) {
        this.x = x;
        this.y = y;
        this.red = red;
        this.green = green;
        this.blue = blue;
    }
    public void setFontColor(Short fontColor) {
        this.fontColor = fontColor;
    }
    public Integer getX() {
        return x;
    }

    public Integer getY() {
        return y;
    }

    public Short getIndexColor() {
        return indexColor;
    }
    public Integer getRed() {
        return red;
    }
    public Integer getGreen() {
        return green;
    }
    public Integer getBlue() {
        return blue;
    }
    public Short getFontColor() {
        return fontColor;
    }
}

/**
 * 自定义表头样式拦截器
 *
 * @since 2022-07-21 14:26
 */
public class CustomHeadWriteHandler extends AbstractCellStyleStrategy {
    /**
     * 复杂表头自定义样式队列,先进先出,方便存储
     */
    private ArrayBlockingQueue<ComplexHeadStyles> headStylesQueue;
    /**
     * 需要渲染下拉框
     */
    private Map<Integer, String[]> dropdownBox = new HashMap<>();

    /**
     * CellStyle
     */
    private CellStyle cellStyle;
    public CustomHeadWriteHandler(ArrayBlockingQueue<ComplexHeadStyles> headStylesQueue) {
        this.headStylesQueue = headStylesQueue;
    }
    public CustomHeadWriteHandler(ArrayBlockingQueue<ComplexHeadStyles> headStylesQueue, Map<Integer, String[]> dropdownBox) {
        this.headStylesQueue = headStylesQueue;
        this.dropdownBox = dropdownBox;
    }
    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        Sheet sheet = writeSheetHolder.getSheet();
        if (isHead) {
            if (headStylesQueue != null && !headStylesQueue.isEmpty()) {
                ComplexHeadStyles complexHeadStyle = headStylesQueue.peek();
                // 取出队列中的自定义表头信息,与当前坐标比较,判断是否相符
                if (cell.getColumnIndex() == complexHeadStyle.getY() && relativeRowIndex.equals(complexHeadStyle.getX())) {
                    Workbook workbook = sheet.getWorkbook();
                    CellStyle cellStyle = initCellStyleCustom(workbook, complexHeadStyle.getFontColor());
                    if (ObjectUtil.isNotEmpty(complexHeadStyle.getIndexColor())) {
                        //有指定颜色颜色 索引
                        cellStyle.setFillForegroundColor(complexHeadStyle.getIndexColor());
                        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                        cell.setCellStyle(cellStyle);
                    } else {
                        //有指定颜色 RGB
                        if (ObjectUtil.isNotEmpty(complexHeadStyle.getRed()) && ObjectUtil.isNotEmpty(complexHeadStyle.getGreen()) && ObjectUtil.isNotEmpty(complexHeadStyle.getBlue())) {
                            XSSFCellStyle xssfCellStyle = (XSSFCellStyle)workbook.createCellStyle();
                            xssfCellStyle.cloneStyleFrom(cellStyle);
                            xssfCellStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(complexHeadStyle.getRed(), complexHeadStyle.getGreen(), complexHeadStyle.getBlue())));
                            xssfCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                            cell.setCellStyle(xssfCellStyle);
                        }
                    }
                    // 样式出队
                    headStylesQueue.poll();
                }
            }
        } else {
            cell.setCellStyle(cellStyle);
        }
        //设置下拉框选项
        DataValidationHelper helper = sheet.getDataValidationHelper();
        for (Map.Entry<Integer, String[]> entry : dropdownBox.entrySet()) {
            /***起始行、终止行、起始列、终止列**/
            CellRangeAddressList addressList = new CellRangeAddressList(1, 9999, entry.getKey(), entry.getKey());
            /***设置下拉框数据**/
            DataValidationConstraint constraint = helper.createExplicitListConstraint(entry.getValue());
            DataValidation dataValidation = helper.createValidation(constraint, addressList);
            /***处理Excel兼容性问题**/
            if (dataValidation instanceof XSSFDataValidation) {
                dataValidation.setSuppressDropDownArrow(true);
                dataValidation.setShowErrorBox(true);
            } else {
                dataValidation.setSuppressDropDownArrow(false);
            }
            sheet.addValidationData(dataValidation);
        }
    }

    @Override
    protected void initCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName("微软雅黑");
        font.setFontHeightInPoints((short)11);
        font.setColor(IndexedColors.BLACK.getIndex());
        style.setFont(font);
        DataFormat dataFormat = workbook.createDataFormat();
        style.setDataFormat(dataFormat.getFormat("@"));
        this.cellStyle = style;
    }
    @Override
    protected void setHeadCellStyle(Cell cell, Head head, Integer relativeRowIndex) {

    }
    @Override
    protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) {

    }

    private CellStyle initCellStyleCustom(Workbook workbook, Short fontColor) {
        CellStyle style = workbook.createCellStyle();
        style.setBorderBottom(BorderStyle.THIN);   // 下边框
        style.setBorderLeft(BorderStyle.THIN);     // 左边框
        style.setBorderTop(BorderStyle.THIN);      // 上边框
        style.setBorderRight(BorderStyle.THIN);    // 右边框

        Font font = workbook.createFont();
        font.setFontName("微软雅黑");
        font.setBold(true);
        font.setFontHeightInPoints((short)13);
        font.setColor(IndexedColors.BLACK.getIndex());
        if (ObjectUtil.isNotNull(fontColor)) {
            font.setColor(fontColor);
        }
        style.setFont(font);
        style.setAlignment(LEFT);
        DataFormat dataFormat = workbook.createDataFormat();
        return style;
    }
}
/**
 * excel 工具类
 */
public class ExcelUtils {

    /**
     * excel 导出样式 默认
     *
     * @return
     */
    public static WriteHandler setExcelStyle() {
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景设置为橙色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setColor(IndexedColors.WHITE.getIndex());
        headWriteFont.setFontName("微软雅黑");
        headWriteFont.setFontHeightInPoints((short)13);
        headWriteCellStyle.setWriteFont(headWriteFont);
        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        WriteFont contentWriteFont = new WriteFont();
        contentWriteFont.setFontName("微软雅黑");
        contentWriteFont.setFontHeightInPoints((short)11);
        contentWriteFont.setColor(IndexedColors.BLACK.getIndex());
        // 字体大小
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    }

    /**
     * 导出文件时为Writer生成OutputStream
     *
     * @param fileName 文件名
     * @param response response
     * @return 流
     */
    public static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
        try {
            fileName = URLEncoder.encode(fileName, "utf-8");
            response.setCharacterEncoding("utf8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + fileName + ".xlsx");
            return response.getOutputStream();
        } catch (IOException e) {
            throw new Exception("导出excel表格失败!", e);
        }
    }

     /**
     * excel 导出样式 测试
     *
     * @return
     */
    public static WriteHandler setTestTemplateSheet0() {
        // 设置表头样式队列【先进先出】
        ArrayBlockingQueue<ComplexHeadStyles> complexHeadStylesArrayBlockingQueue = new ArrayBlockingQueue<>(3);

        /**
         * 颜色
         */
        complexHeadStylesArrayBlockingQueue.add(new ComplexHeadStyles(0, 0, 102, 255, 255));
        complexHeadStylesArrayBlockingQueue.add(new ComplexHeadStyles(0, 1, IndexedColors.ORANGE.getIndex()));
        complexHeadStylesArrayBlockingQueue.add(new ComplexHeadStyles(0, 2, IndexedColors.GREY_25_PERCENT.getIndex()));
        /**
         * 下拉框
         */
        Map<Integer, String[]> dropdownBox = new HashMap<>();
        dropdownBox.put(0,new String[]{"选项1","选项2"});
        CustomHeadWriteHandler headStyleWriteHandler = new CustomHeadWriteHandler(complexHeadStylesArrayBlockingQueue,dropdownBox);
        return headStyleWriteHandler;
    }

    public static List<List<String>> getTestHeader0(List<List<Object>> list0) {
        List<List<String>> list = Lists.newArrayList();
        List<String> head0 = Lists.newArrayList("第一列");
        List<String> head1 = Lists.newArrayList("第二列");
        List<String> head2 = Lists.newArrayList("第三列");
        list.add(head0);
        list.add(head1);
        list.add(head2);
        List<Object> row1 = Lists.newArrayList("111", "222", "333");
        list0.add(row1);
        return list;
    }

    public static ByteArrayOutputStream getExcelTestOut(HttpServletResponse response) {
        ExcelWriter excelWriter = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            if (ObjectUtil.isNotEmpty(response)) {
                excelWriter = EasyExcel.write(getOutputStream("test", response)).registerWriteHandler(setExcelStyle()).build();
            } else {
                excelWriter = EasyExcel.write(out).registerWriteHandler(setExcelStyle()).build();
            }

            List<List<Object>> list0 = Lists.newArrayList();
            List<List<String>> header0 = getTestHeader0(list0);
            //获取sheet对象
            WriteSheet sheet0 = EasyExcel.writerSheet(0, "test").head(header0).registerWriteHandler(ExcelUtils.setTestTemplateSheet0()).build();
            excelWriter.write(list0, sheet0);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            excelWriter.finish();
        }
        return out;
    }

    public static void main(String[] args) throws IOException {
        ByteArrayOutputStream excelTestOut = getExcelTestOut(null);
        //建立文件
        File file = new File("D:\\test.xlsx");
        if (file.exists()) {
            System.out.println("文件已存在");
            return;
        }
        file.createNewFile();
        FileOutputStream fileOutputStream = new FileOutputStream(file.getPath());
        fileOutputStream.write(excelTestOut.toByteArray());
        fileOutputStream.close();
    }
}

excel 效果展示
在这里插入图片描述

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
对于复杂自定义表头导出,可以使用EasyExcel的注解`@ExcelProperty`来实现。具体步骤如下: 1. 创建表头实体类,使用`@ExcelProperty`注解来定义表头名称和对应的字段。 ```java public class ComplexHeadData { @ExcelProperty({"主标题", "名称"}) private String name; @ExcelProperty({"主标题", "数量"}) private Integer number; @ExcelProperty({"主标题", "价格"}) private Double price; @ExcelProperty({"次标题", "子名称"}) private String subName; @ExcelProperty({"次标题", "子数量"}) private Integer subNumber; @ExcelProperty({"次标题", "子价格"}) private Double subPrice; // 省略getter和setter方法 } ``` 2. 创建导出数据集合,并将数据集合和表头实体类传入`EasyExcel.write()`方法中,使用`Sheet`对象来设置表头。 ```java List<ComplexHeadData> data = ... Sheet sheet = new Sheet(1, 0, ComplexHeadData.class); // 设置主标题行 List<List<String>> head = new ArrayList<>(); head.add(Arrays.asList("主标题", "名称", "数量", "价格")); // 设置次标题行 head.add(Arrays.asList("次标题", "子名称", "子数量", "子价格")); // 设置表头样式 WriteCellStyle headStyle = new WriteCellStyle(); // ... 设置样式 // 设置主标题行的样式 WriteCellStyle mainHeadStyle = new WriteCellStyle(headStyle); mainHeadStyle.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex()); // 设置次标题行的样式 WriteCellStyle subHeadStyle = new WriteCellStyle(headStyle); subHeadStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); // 设置主标题行和次标题行的样式 WriteCellStyle headCellStyle = new WriteCellStyle(); headCellStyle.setWrapped(true); headCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER); headCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); headCellStyle.setMainHeadStyle(mainHeadStyle); headCellStyle.setSubHeadStyle(subHeadStyle); // 设置表头 sheet.setHead(head); sheet.setHeadStyle(headCellStyle); // 写入数据到Excel EasyExcel.write(outputStream, ComplexHeadData.class).sheet().doWrite(data); ``` 通过以上步骤,即可实现复杂自定义表头导出。需要注意的是,`@ExcelProperty`注解中的数组参数表示表头的层级关系,数组的第一个元素为主标题,第二个元素为次标题,以此类推。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值