POI导出Excel设置背景色踩坑,解决背景色全黑(无效)的问题及指定列添加背景色,自定义颜色

本文介绍了使用Apache POI在Java中导出Excel时遇到的背景色设置问题,包括自定义颜色、背景色全黑的解决方法以及如何指定列添加背景色。关键在于设置填充样式为SOLID_FOREGROUND,并使用setFillForegroundColor方法来设置颜色。

一.自定义颜色

话不多说,上代码,这里改的是字体颜色,一些信息放在注释中了

        String str = "#666666";//灰色--->16进制颜色信息,网上百度就行,有特定的网站例如:https://www.tpyyes.com/tool/rgb.html
		//处理把它转换成十六进制并放入一个数
        int[] color=new int[3];
        color[0]=Integer.parseInt(str.substring(1, 3), 16);
        color[1]=Integer.parseInt(str.substring(3, 5), 16);
        color[2]=Integer.parseInt(str.substring(5, 7), 16);
		//自定义颜色
        HSSFPalette palette = workbook.getCustomPalette();
        palette.setColorAtIndex(HSSFColor.GOLD.index,(byte)color[0], (byte)color[1], (byte)color[2]);//此处颜色名可随意使用,但是下面引用的时候要保持一致
            // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体颜色为红色
        font.setColor(HSSFColor.GOLD.index);//颜色名字与上面自定义的保持一致

二.背景色全黑(无效)的问题解决在这里插入图片描述

poi设置背景色的时候,一定要设置填充样式(setFillPattern方法),要达到上图所示效果,填充样式一定要设置为SOLID_FOREGROUND

  		//设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);//设置前景填充样式
        style.setFillForegroundColor(IndexedColors. GREY_25_PERCENT.index);//前景填充色

注意:如果改任何背景色,均为黑色时,及设置背景色无效,原因时因为poi代码问题
如果填充颜色时使用setFillBackgroundColor方法,则颜色设置无效,可尝试改为setFillForegroundColor方法
本人遇到的异常方式:

		style.setFillBackgroundColor(IndexedColors. GREY_25_PERCENT.index);// 设置背景颜色
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

三.指定列添加背景色

在指定列添加背景颜色,要在将查询出的数据设置到sheet对应的单元格中的循环里面进行的,以上图的指标名称列为例,下面添加代码片段,稍后贴出完整代码

	HSSFCellStyle style = this.getStyle(workbook);                    //单元格样式对象(普通)
 	HSSFCellStyle styleColor = this.getStyleColor(workbook);         //单元格样式对象有色
    //将查询出的数据设置到sheet对应的单元格中
            for (int i = 0; i < dataList.size(); i++) {
                HashMap<String, Object> obj = dataList.get(i);//遍历每个对象
                HSSFRow row = sheet.createRow(i + 2);//创建所需的行数
                int cellIndex = 0;
                for (Map.Entry<String, String> entry : keyNameMap.entrySet()) {
                    HSSFCell cell = null;
                    cell = row.createCell(cellIndex, HSSFCell.CELL_TYPE_STRING);
                    cell.setCellValue(obj.get(entry.getKey()).toString());
                    cell.setCellStyle(style);
                    //此处是指定列添加背景色
                    HSSFCell cell1 = row.createCell(0,HSSFCell.CELL_TYPE_STRING);//指定列是第几列
                    cell1.setCellStyle(styleColor);//指定列的样式设置
                    cell1.setCellValue(obj.get("指标名称").toString());//指定列的内容赋值,传的是列名
                    ++cellIndex;
                }

            }

四.完整的代码

注:背景色代码在getStyleColor方法中,注释中的不对

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.apache.shiro.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version 1.0
 * @name
 * @description 
 * @date 20210616
 */
public class ExportExcelUtil {
    /**
     * 显示的导出表的标题
     */
    private String title;


    /**
     * 需要导出的数据集合
     */
    private List<HashMap<String, Object>> dataList = new ArrayList<HashMap<String, Object>>();

    private LinkedHashMap<String, String> keyNameMap = new LinkedHashMap<>();
    /**
     * 输入流对象
     */
    private HttpServletRequest request;

    /**
     * 输出流对象
     */
    private HttpServletResponse response;

    /**
     * 合并单元格
     */
    private LinkedList<int[]> mergeRowsList;


    /**
     * @description 构造方法,传入要导出的数据
     */
    public BatchMaintenanceRiskIndicatorsExportExcelUtil(String title, List<HashMap<String, Object>> dataList, HttpServletRequest request, HttpServletResponse response, LinkedHashMap<String, String> keyNameMap) {
        this.title = title;
        this.dataList = dataList;
        this.request = request;
        this.response = response;
        this.keyNameMap = keyNameMap;
    }

    public void export(String fileName) throws Exception {

        try {
            HSSFWorkbook workbook = new HSSFWorkbook();                        // 创建工作簿对象
            HSSFSheet sheet = workbook.createSheet();                     // 创建工作表

            // 产生表格标题行
            HSSFRow rowm = sheet.createRow(0);
            HSSFCell cellTiltle = rowm.createCell(0);

            //设置标题和单元格样式
            HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);  //获取列头样式对象
            HSSFCellStyle style = this.getStyle(workbook);                    //单元格样式对象
            HSSFCellStyle styleColor = this.getStyleColor(workbook);                    //单元格样式对象有色

            //合并单元格
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, (keyNameMap.size() - 1)));

            if (!CollectionUtils.isEmpty(mergeRowsList)) {
                for (int[] a : mergeRowsList) {
                    sheet.addMergedRegion(new CellRangeAddress(a[0], a[1], a[2], a[3]));
                }
            }

            cellTiltle.setCellStyle(columnTopStyle);
            cellTiltle.setCellValue(title);


            // 定义所需列数
            int columnNum = keyNameMap.size();
            HSSFRow rowRowName = sheet.createRow(1);                 // 在索引1的位置创建行(最顶端的行开始的第2行)

            HSSFCellStyle rowTopStyle = this.getRowTopStyle(workbook);  //获取列头样式对象
            // 将列头设置到sheet的单元格中
            int sizeIndex = 0;
            for (Map.Entry<String, String> entry : keyNameMap.entrySet()) {
                HSSFCell cellRowName = rowRowName.createCell(sizeIndex);                  //创建列头对应个数的单元格
                cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);                //设置列头单元格的数据类型
                HSSFRichTextString text = new HSSFRichTextString(entry.getValue());
                cellRowName.setCellValue(text);                                    //设置列头单元格的值
                cellRowName.setCellStyle(rowTopStyle);
                ++sizeIndex;
            }




            //将查询出的数据设置到sheet对应的单元格中
            for (int i = 0; i < dataList.size(); i++) {
                HashMap<String, Object> obj = dataList.get(i);//遍历每个对象
                HSSFRow row = sheet.createRow(i + 2);//创建所需的行数
                int cellIndex = 0;
                for (Map.Entry<String, String> entry : keyNameMap.entrySet()) {
                    HSSFCell cell = null;
                    cell = row.createCell(cellIndex, HSSFCell.CELL_TYPE_STRING);
                    cell.setCellValue(obj.get(entry.getKey()).toString());
                    cell.setCellStyle(style);
                    HSSFCell cell1 = row.createCell(0,HSSFCell.CELL_TYPE_STRING);
                    cell1.setCellStyle(styleColor);
                    cell1.setCellValue(obj.get("指标名称").toString());
                    ++cellIndex;
                }

            }


            sheet.autoSizeColumn(0);
            //让列宽随着导出的列长自动适应
            for (int colNum = 0; colNum < columnNum; colNum++) {
                int columnWidth = sheet.getColumnWidth(colNum) / 256;
                for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                    HSSFRow currentRow;
                    //当前行未被使用过
                    if (sheet.getRow(rowNum) == null) {
                        currentRow = sheet.createRow(rowNum);
                    } else {
                        currentRow = sheet.getRow(rowNum);
                    }
                    if (currentRow.getCell(colNum) != null) {
                        //取得当前的单元格
                        HSSFCell currentCell = currentRow.getCell(colNum);
                        //如果当前单元格类型为字符串
                        if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                            int length = currentCell.getStringCellValue().getBytes().length;
                            if (columnWidth < length) {
                                //将单元格里面值大小作为列宽度
                                columnWidth = length;
                            }
                        }
                    }
                }
                //再根据不同列单独做下处理
                if (colNum == 11|| colNum==12) {
                    sheet.setColumnWidth(colNum,(columnWidth + 6)*256);
                } else{
                    sheet.setColumnWidth(colNum,(columnWidth + 4 )*256);
                }

            }

            if (workbook != null) {
                try {

                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("multipart/form-data");
                    String userAgent = request.getHeader("User-Agent");
                    byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8"); // fileName.getBytes("UTF-8")处理safari的乱码问题
                    String fileNameEncode = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
                    response.setHeader("Content-disposition",
                            String.format("attachment; filename=\"%s\"", fileNameEncode + ".xls"));
                    OutputStream out1 = response.getOutputStream();
                    workbook.write(out1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @description 标题行的单元格样式
     */
    public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {

        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short) 10);
        //字体加粗
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //设置字体名字
        font.setFontName("Courier New");
        //设置字体颜色为红色
        font.setColor(HSSFColor.RED.index);
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
        //设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
//        style.setFillPattern(HSSFCellStyle.FINE_DOTS );
//        style.setFillBackgroundColor(HSSFColor.GREEN.index);// 设置背景颜色
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为左对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        return style;
    }


    /**
     * @description 标题列的单元格样式
     */
    public HSSFCellStyle getRowTopStyle(HSSFWorkbook workbook) {

        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short) 11);
        //字体加粗
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //设置字体名字
        font.setFontName("Courier New");
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
        //设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);

        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        return style;
    }

    /**
     * @description 列数据信息单元格样式
     */
    public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        //font.setFontHeightInPoints((short)10);
        //字体加粗
        //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //设置字体名字
        font.setFontName("Courier New");
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为左对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        return style;
    }


    public static CellStyle getStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
        //设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        //在样式用应用设置的字体;
//            style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        return style;
    }


    //日期格式化
    public static String formatDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String newDate = sdf.format(date);
        return newDate;
    }


    //未处理公式
    public static String getCellValue(XSSFCell cell) {
        if (cell == null) {
            return null;
        }

        switch (cell.getCellType()) {
            case XSSFCell.CELL_TYPE_STRING:
                return cell.getRichStringCellValue().getString().trim();
            case XSSFCell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    return sdf.format(cell.getDateCellValue());
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case XSSFCell.CELL_TYPE_BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case XSSFCell.CELL_TYPE_FORMULA:
                return cell.getCellFormula();
            default:
                return null;
        }
    }


    public static void copySheet(XSSFWorkbook workbook, XSSFSheet sheet, XSSFSheet sheetCreat) {
        MergerRegion(sheetCreat, sheet);
        int firstRow = sheet.getFirstRowNum();
        int lastRow = sheet.getLastRowNum();
        for (int a = firstRow; a <= lastRow; a++) {
            // 创建新建excel Sheet的行
            XSSFRow rowCreat = sheetCreat.createRow(a);
            // 取得源有excel Sheet的行
            XSSFRow row = sheet.getRow(a);
            rowCreat.setRowStyle(row.getRowStyle());
            // 单元格式样
            int firstCell = row.getFirstCellNum();
            int lastCell = row.getLastCellNum();
            for (int j = firstCell; j < lastCell; j++) {
                // 自动适应列宽
                sheetCreat.autoSizeColumn(j);
                XSSFCell newCell = rowCreat.createCell(j);
                String strVal = "";
                if (row.getCell(j) == null) {
                } else {
                    strVal = row.getCell(j).getStringCellValue();
                }
                newCell.getRow().setHeight(row.getCell(j).getRow().getHeight());
                XSSFCellStyle toStyle = workbook.createCellStyle();
                copyCellStyle(row.getCell(j).getCellStyle(), toStyle);
                newCell.setCellStyle(toStyle);
                newCell.setCellValue(strVal);

            }
        }
    }

    public static void copyCellStyle(XSSFCellStyle fromStyle, XSSFCellStyle toStyle) {

        toStyle.cloneStyleFrom(fromStyle);
        toStyle.setFillForegroundColor(fromStyle.getFillForegroundColor());
        toStyle.setFillPattern(fromStyle.getFillPattern());
        toStyle.setFillBackgroundColor(fromStyle.getFillBackgroundColor());
    }

    /**
     *   * 复制原有sheet的合并单元格到新创建的sheet
     *   *
     *   * @param sheetCreat
     *   *      新创建sheet
     *   * @param sheet
     *   *      原有的sheet
     */


    private static void MergerRegion(XSSFSheet sheetCreat, XSSFSheet sheet) {
        int sheetMergerCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergerCount; i++) {
            CellRangeAddress mergedRegion = sheet.getMergedRegion(i);
            sheetCreat.addMergedRegion(mergedRegion);
        }


    }

    /**
     * @description 列数据信息单元格样式2
     */
    public HSSFCellStyle getStyleColor(HSSFWorkbook workbook) {

        String str = "#666666";
//处理把它转换成十六进制并放入一个数
        int[] color=new int[3];
        color[0]=Integer.parseInt(str.substring(1, 3), 16);
        color[1]=Integer.parseInt(str.substring(3, 5), 16);
        color[2]=Integer.parseInt(str.substring(5, 7), 16);
//自定义颜色
        HSSFPalette palette = workbook.getCustomPalette();
        palette.setColorAtIndex(HSSFColor.GOLD.index,(byte)color[0], (byte)color[1], (byte)color[2]);

        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        //font.setFontHeightInPoints((short)10);
        //字体加粗
        //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //设置字体名字
        font.setFontName("Courier New");
        //设置字体颜色为红色
        font.setColor(HSSFColor.GOLD.index);
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        //在样式用应用设置的字体;


/*       style.setFillBackgroundColor(IndexedColors. GREY_25_PERCENT.index);// 设置背景颜色
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);*/

      /* style.setFillBackgroundColor(IndexedColors. SKY_BLUE.index);// 设置背景颜色
        style.setFillPattern(HSSFCellStyle.FINE_DOTS );*/


        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);//设置前景填充样式

        style.setFillForegroundColor(IndexedColors. GREY_25_PERCENT.index);//前景填充色

        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为左对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        return style;
    }

}

<think>根据用户问题,需要实现使用POI导出Excel时,根据十六进制颜色设置单元格背景色。引用[2]提到POI 5.2.3及以上版本支持自定义颜色,因此我们需要使用较新版本的POI。 关键点: 1. 使用XSSFWorkbook(对应.xlsx格式)才能支持自定义颜色。 2. 通过XSSFColor类创建自定义颜色,需要传入RGB值。 3. 设置单元格样式时,注意使用setFillForegroundColor方法,并设置填充模式为FillPatternType.SOLID_FOREGROUND。 步骤: 1. 创建工作簿和工作表。 2. 创建行和单元格。 3. 创建单元格样式。 4. 将十六进制颜色码转换为RGB,并创建XSSFColor对象。 5. 设置样式的填充前景色为自定义颜色,并设置填充模式。 6. 将样式应用到单元格。 注意:十六进制颜色码的格式可能是6位(如"FF0000"代表红色)或8位(带透明度,但我们通常使用后6位作为RGB,忽略前两位的透明度)。在POI中,我们通常使用RGB三字节,也可以使用四字节(带透明度),这里我们假设用户传入的是6位十六进制字符串(不带#前缀,或带#前缀需要去除)。 示例代码: 假设用户传入的十六进制颜色码为字符串(例如:"FF0000"),我们将它转换为RGB字节数组。 转换方法:将6位字符串每两位截取,转换为0-255的整数,然后作为字节数组(注意,XSSFColor的构造函数需要byte数组,且顺序为RGB)。 另外,在POI 5.2.3中,我们可以使用`new XSSFColor(new byte[]{(byte)red, (byte)green, (byte)blue}, null)`。 但是注意:在Java中,byte的范围是-128~127,所以我们需要将0-255的整数转换为对应的byte。由于颜色值是无符号的,我们可以直接强转,因为byte的位模式与int的低8位相同。 完整代码示例: </think> 使用 Apache POI 导出 Excel 时,根据十六进制颜色设置单元格背景色的实现方法如下: ### 解决方案(POI 5.2.3+) ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.*; import java.io.FileOutputStream; public class ExcelColorExporter { public static void main(String[] args) throws Exception { // 1. 创建工作簿和工作表 Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("自定义颜色"); // 2. 创建行和单元格 Row row = sheet.createRow(0); Cell cell = row.createCell(0); cell.setCellValue("自定义背景色"); // 3. 将十六进制颜色码转换为RGB String hexColor = "#FF5733"; // 示例颜色(橙色) byte[] rgb = hexToRgb(hexColor); // 4. 创建自定义颜色 XSSFColor customColor = new XSSFColor(rgb, null); // 使用XSSFColor // 5. 创建单元格样式 CellStyle style = workbook.createCellStyle(); style.setFillForegroundColor(customColor); // 关键设置 style.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 6. 应用样式到单元格 cell.setCellStyle(style); // 7. 导出文件 try (FileOutputStream out = new FileOutputStream("custom_color.xlsx")) { workbook.write(out); } workbook.close(); } // 十六进制转RGB方法 private static byte[] hexToRgb(String hex) { if (hex.startsWith("#")) hex = hex.substring(1); return new byte[] { (byte) Integer.parseInt(hex.substring(0, 2), 16), // R (byte) Integer.parseInt(hex.substring(2, 4), 16), // G (byte) Integer.parseInt(hex.substring(4, 6), 16) // B }; } } ``` ### 关键点说明 1. **版本要求**:必须使用 POI 5.2.3 及以上版本(`XSSFColor` 支持自定义 RGB)[^2] 2. **颜色转换**: - 十六进制格式需为 `#RRGGBB` 或 `RRGGBB` - 转换后得到 RGB 字节数组 `[R, G, B]` 3. **样式设置**: ```java style.setFillForegroundColor(customColor); // 设置自定义颜色 style.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 必须设置填充模式 ``` 4. **注意事项**: - 仅支持 `.xlsx` 格式(`XSSFWorkbook`) - 旧版 POI(如 4.x)只能使用预设颜色枚举 `IndexedColors`[^3] - 颜色值范围:0-255(超出范围会自动截断) ### 效果验证 生成的 Excel 单元格将显示指定颜色: ![自定义背景色效果](https://i-blog.csdnimg.cn/blog_migrate/890c28ba6174a70e08eaf91779cad1df.png) [^1]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值