POI修改excel背景颜色踩坑

1 篇文章 0 订阅

根据业务需求,导出excel需要隔行变色,使用pom如下

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.15</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>

直接使用行样式的方法是不行的 row1.setRowStyle(style),只能将一行没有数据的空白格变色,有数据的单元格不会受影响

public static void writeExcelStyle(HttpServletResponse response, List<String> header, List<List<String>> datas) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");
        Row row = sheet.createRow(0);
        for (int i = 0; i < header.size(); i++) {
            row.createCell(i).setCellValue(header.get(i));
        }
        for (int i = 0; i < datas.size(); i++) {
            Row row1 = sheet.createRow(i + 1);
            if (i%2 != 0){
                CellStyle style = workbook.createCellStyle();
                style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
                style.setFillPattern(CellStyle.SOLID_FOREGROUND);
                row1.setRowStyle(style);
            }
            List<String> data = datas.get(i);
            // 创建单元格设值
            for (int j = 0; j < data.size(); j++) {
                Cell cell = row1.createCell(j);
                cell.setCellValue(data.get(j));
            }
        }
        buildExcelDocument("File.xlsx", workbook, response);
    }

修改代码,改为单元格样式 cell.setCellStyle(style):单独为每个单元格设置背景颜色

        for (int i = 0; i < datas.size(); i++) {
            Row row1 = sheet.createRow(i + 1);
            row1.setHeightInPoints(20);
            List<String> data = datas.get(i);
            // 创建单元格设值
            for (int j = 0; j < data.size(); j++) {
                Cell cell = row1.createCell(j);
                cell.setCellValue(data.get(j));
                if (i%2 != 0){
                    CellStyle style = workbook.createCellStyle();
                    style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
                    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
                    cell.setCellStyle(style);
                }
            }
        }

最后切记一定要用 style.setFillForegroundColor,而不是 style.setFillBackgroundColor(),两者长得相似,且后者的字面意思更贴近“背景颜色”。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值