`
javapolo
  • 浏览: 130271 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

poi 自定义颜色设置

 
阅读更多
    最近在项目的开发中使用到了apache poi,该组件可以让我们方便的操作excell,该工具非常容易上手,但使用过程中也发现了一些问题,就是当你操作excell文档为其设置颜色时,该文档所能设的颜色最多只能是56种(poi自身提供的系统颜色,例如红,黄等,我们可以通过对已有的色块进行调色达到我们自定义颜色的目的,在PaletteRecord类里面初始化),也就是说poi加载到内存之后,它所维护的只有56块色块,且系统只有一份,所以在一个excell生成过程中,它必须锁定该所有的调色块,待该excell文件生成之后,才能将该资源释放,供下个线程使用,而且在设置excell颜色过程中我们必须标识哪些调色块已经使用,哪些没用,这样我们才能防止调好的背景颜色被覆盖,在poi中自定义颜色一般通过HSSFPalette(调色板)对象调用setColorAtIndex(short index, byte red, byte green, byte blue)方法,
   /**  
     * @param 设置颜色块的索引,从 0x8 到 0x40
     * @param red 红色, between 0 and 255 inclusive
     * @param green 绿色, between 0 and 255 inclusive
     * @param blue 蓝色, between 0 and 255 inclusive
     */
    public void setColorAtIndex(short index, byte red, byte green, byte blue)
    {
        _palette.setColor(index, red, green, blue);
    }
通过该方法对调色块进行调色,调完色后,则该调色块对应的颜色就是通过最新的rgb值调出来的,下一步,例如你要设某单元格的背景色,你只要调用样式style.setFillForegroundColor(index)就可以了,在控制调色块的使用情况时可以采用List<Map>的集合来实现,通过Map<索引,使用情况>来标识一个色块的使用情况,
public class ColorIncreaseUtil {

public static int colorindex;
public static Map<String, Integer> maps;

/**
* 开始颜色索引
*/
public static void beginColorIndex() {
maps = new HashMap<String, Integer>();
for (int i = 8; i <= 64; i++) {
maps.put(i + "", 0);
}
colorindex = 8;
}

/**
* 颜色索引值增加
*/
public static short getColorIndexIncrease() {

if (colorindex > 64)
return 0;
colorindex = colorindex + 1;
while (maps.get("" + (colorindex)).intValue() == 1) {

colorindex = colorindex + 1;
}
return (short) colorindex;

}

/**
* 设置摸个颜色板已经占用
*
* @param index
*/
public static void setFlag(short index) {
maps.put(index + "", 1);
}
通过这样设置,我们就可以方便的定义我们的颜色了。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics