POI setting Cell Background to a Custom Color

后端 未结 6 856
野性不改
野性不改 2020-12-25 11:03

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

HSSFPalette palette = aWorkBook.getCustom         


        
6条回答
  •  轮回少年
    2020-12-25 11:29

    As pointed in Vlad's answer, you are running out of free color slots. One way to get around that would be to cache the colors: whenever you try a RGB combination, the routine should first check if the combination is in the cache; if it is in the cache, then it should use that one instead of creating a new one from scratch; new colors would then only be created if they're not yet in cache.

    Here's the implementation I use; it uses XSSF plus Guava's LoadingCache and is geared towards generationg XSSF colors from CSS rgb(r, g, b) declarations, but it should be relatively trivial to adapt it to HSSF:

        private final LoadingCache colorsFromCSS = CacheBuilder.newBuilder()
                .build(new CacheLoader() {
    
                    private final Pattern RGB = Pattern.compile("rgb\\(\\s*(\\d+)\\s*, \\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)");
    
                    @Override
                    public XSSFColor load(String style) throws Exception {
                        Matcher mat = RGB.matcher(style);
                        if (!mat.find()) {
                            throw new IllegalStateException("Couldn't read CSS color: " + style);
                        }                       
                        return new XSSFColor(new java.awt.Color(
                                Integer.parseInt(mat.group(1)), 
                                Integer.parseInt(mat.group(2)), 
                                Integer.parseInt(mat.group(3))));
                    }
    
                });
    

    Perhaps someone else could post a HSSF equivalent? ;)

提交回复
热议问题