EasyExcel 单元格背景颜色、字体颜色使用2种设置颜色方法(IndexedColors中定义的颜色,自定义RGB颜色)实现

1 Maven配置  

        <!--hutool工具包-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.5.1</version>
        </dependency>
         <!-- EasyExcel文档处理工具 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.8</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

2 调试代码

    /**
     * 导出(单元格背景颜色、字体颜色使用2种设置颜色方法(IndexedColors中定义的颜色,自定义RGB颜色)实现)
     *
     * @param response
     */
    @GetMapping("/exportStyleColor")
    public void exportStyleColor(HttpServletResponse response) {
        try {
            //生成表格数据
            List<List<Object>> dataList = new ArrayList<>();
            dataList.add(new ArrayList<>(Arrays.asList(new Object[]{"表头11", "表头2", "表头3", "表头4"})));
            dataList.add(new ArrayList<>(Arrays.asList(new Object[]{"表头1", "表头2", "表头3", "表头4"})));
            dataList.add(new ArrayList<>(Arrays.asList(new Object[]{"表头31", "表头2", "表头3", "表头4"})));
            //导出文件
            String fileName = new String("文件名称.xlsx".getBytes(), "UTF-8");

            List<CellStyleModel> cellStyleList = new ArrayList<>();
            //设置字体颜色
            //使用IndexedColors中定义的颜色
            cellStyleList.add(CellStyleModel.createFontColorCellStyleModel("模板", 0, 0, IndexedColors.BLUE));
            //使用自定义RGB颜色
            cellStyleList.add(CellStyleModel.createFontColorCellStyleModel("模板", 0, 1, 119, 119, 119));
            XSSFColor fontColor = CellStyleModel.getRGBColor(225, 0, 0);
            cellStyleList.add(CellStyleModel.createFontColorCellStyleModel("模板", 0, 2, fontColor));

            //设置单元格背景颜色
            //使用IndexedColors中定义的颜色
            cellStyleList.add(CellStyleModel.createBackgroundColorCellStyleModel("模板", 1, 0, IndexedColors.PINK));
            //使用自定义RGB颜色
            cellStyleList.add(CellStyleModel.createBackgroundColorCellStyleModel("模板", 1, 1, 119, 119, 119));
            XSSFColor backgroundColor = CellStyleModel.getRGBColor(225, 0, 0);
            cellStyleList.add(CellStyleModel.createBackgroundColorCellStyleModel("模板", 1, 2, backgroundColor));

            response.addHeader("Content-Disposition", "filename=" + fileName);
            //设置类型,扩展名为.xls
            response.setContentType("application/vnd.ms-excel");
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(new CustomCellStyleHandler(cellStyleList)).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
            excelWriter.write(dataList, writeSheet);
            //千万别忘记finish 会帮忙关闭流
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

3 调试结果

注:

(1)有关字体样式更详细的设置请查看以下博客。

EasyExcel 设置字体样式(字体、字体大小、字体颜色、字体加粗、字体斜体、字体下划线、字体上标下标、字体删除线)icon-default.png?t=M85Bhttps://blog.csdn.net/qq_38974638/article/details/117388442

(2)有关CellStyleModel和CustomCellStyleHandler的源码请查看以下博客。

EasyExcel 批量设置单元格样式(字体样式、背景颜色)icon-default.png?t=M85Bhttps://blog.csdn.net/qq_38974638/article/details/114841208

旭东怪的个人空间_哔哩哔哩_Bilibili旭东怪,人生低谷不可怕,可怕的是坚持不到人生转折点的那一天;旭东怪的主页、动态、视频、专栏、频道、收藏、订阅等。哔哩哔哩Bilibili,你感兴趣的视频都在B站。https://space.bilibili.com/484264966?spm_id_from=333.1007.0.0 

### 如何在 EasyExcel设置自定义单元格背景色 为了实现EasyExcel设置自定义单元格背景色的功能,可以采用 `CellStyleStrategy` 类来创建一个监听器并实现 `CellWriteHandler` 接口中的 `afterCellDispose` 方法。通过这种方式可以在写入 Excel 文件的过程中动态地应用所需的样式。 下面是一个具体的例子展示怎样完成这项工作: #### 创建 CellStyleStrategy 的子类 首先需要构建一个新的类继承于 `CellStyleStrategy` 并覆盖其方法以适应特定需求: ```java public class CustomCellStyleStrategy extends CellStyleStrategy { public CustomCellStyleStrategy(WriteCellStyle headWriteCellStyle, WriteCellStyle contentWriteCellStyle) { super(headWriteCellStyle, contentWriteCellStyle); } @Override protected void afterCellDispose(Cell cellResult, Head head, Integer relativeRowIndex, Boolean isHead, List<CellData> cellDataList, WriteSheetHolder writeSheetHolder, List<List<String>> cacheCurrentRowDatas) { // 获取当前的工作表对象 Sheet sheet = writeSheetHolder.getSheet(); Workbook workbook = sheet.getWorkbook(); // 定义新的单元格样式 CellStyle style = workbook.createCellStyle(); // 设置背景颜色 (这里使用的是 RGB 颜色) HSSFColor.HSSFColorPredefined color = HSSFColor.HSSFColorPredefined.LIGHT_GREEN; short index = IndexedColors.LIGHT_GREEN.getIndex(); style.setFillForegroundColor(index); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 应用到指定的单元格上 cellResult.setCellStyle(style); // 调用父类的方法继续处理其他逻辑 super.afterCellDispose(cellResult, head, relativeRowIndex, isHead, cellDataList, writeSheetHolder, cacheCurrentRowDatas); } } ``` 这段代码展示了如何利用 `CellStyleStrategy` 来定制化每一个被写出的数据项所对应的单元格样式[^3]。 #### 使用该策略实例化 writer 对象时传入配置参数 当准备向 Excel 文档中添加数据之前,应该先准备好上述提到过的 `CustomCellStyleStrategy` 实例,并将其作为参数传递给 Writer 构造函数或相应的工厂方法之一。 ```java // 准备头部样式和内容样式 WriteCellStyle headWriteCellStyle = new WriteCellStyle(); headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER); WriteCellStyle contentWriteCellStyle = new WriteCellStyle(); contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 初始化自定义样式的策略 CellStyleStrategy customCellStyleStrategy = new CustomCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle); // 将此策略应用于 EasyExcel.WriterBuilder 或者类似的构造过程中... EasyExcel.write(fileName).registerWriteHandler(customCellStyleStrategy)...build(); ``` 以上就是关于如何在 EasyExcel 中设定自定义单元格背景色的一个基本介绍以及实践指南[^2]。
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值