POI将单元格背景设置为自定义颜色 [英] POI setting Cell Background to a Custom Color

查看:1006
本文介绍了POI将单元格背景设置为自定义颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为单元格的背景设置自定义颜色.
我使用HSSFWorkbook(不能使用其他任何东西).

I want to set custom color to a cell's background.
I use HSSFWorkbook (can't use anything else).

HSSFPalette palette = aWorkBook.getCustomPalette();             
Color col = new Color(backgroundColor);                     
HSSFColor myColor  = palette.addColor((byte) 10, (byte) 11, (byte) 12); 

我收到此错误:java.lang.RuntimeException: Could not find free color index

推荐答案

由于托盘已满,您会收到此错误.您需要做的是覆盖预设颜色. 这是我正在使用的功能的示例:

You get this error because pallete is full. What you need to do is override preset color. Here is an example of function I'm using:

public HSSFColor setColor(HSSFWorkbook workbook, byte r,byte g, byte b){
    HSSFPalette palette = workbook.getCustomPalette();
    HSSFColor hssfColor = null;
    try {
        hssfColor= palette.findColor(r, g, b); 
        if (hssfColor == null ){
            palette.setColorAtIndex(HSSFColor.LAVENDER.index, r, g,b);
            hssfColor = palette.getColor(HSSFColor.LAVENDER.index);
        }
    } catch (Exception e) {
        logger.error(e);
    }

    return hssfColor;
}

然后将其用作背景颜色:

And later use it for background color:

HSSFColor lightGray =  setColor(workbook,(byte) 0xE0, (byte)0xE0,(byte) 0xE0);
style2.setFillForegroundColor(lightGray.getIndex());
style2.setFillPattern(CellStyle.SOLID_FOREGROUND);

这篇关于POI将单元格背景设置为自定义颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆