POI 自定義16進制顏色導出

今天導入一個Excel 要求什麼格式導入就怎麼顯示,包括字體 顏色,還要怎麼導出。這個poi導入的是16進制顏色,導出比較麻煩。具體參考以下代碼吧

    private CellStyle createStyle(Workbook wb, ExcelCellStyle excelCellStyle) {
        if(styleMap.get(excelCellStyle.getBgColor())!=null)
            return styleMap.get(excelCellStyle.getBgColor());
        CellStyle style = wb.createCellStyle();
        Font titleFont = wb.createFont();
        //titleFont.setFontHeightInPoints((short)48);
        //titleFont.setColor(IndexedColors.DARK_BLUE.getIndex());
        style = wb.createCellStyle();
        String colorStr = excelCellStyle.getBgColor();
        if (colorStr.length() > 6)
            colorStr = colorStr.substring(2);
        HSSFPalette palette = ((HSSFWorkbook) wb).getCustomPalette();//replacing the standard red with freebsd.org red
        palette.setColorAtIndex((short) 9,
                (byte) convertHexToNumber(colorStr.substring(0, 2)),//RGB red
                (byte) convertHexToNumber(colorStr.substring(2, 4)),//RGB green
                (byte) convertHexToNumber(colorStr.substring(4, 6)) //RGB blue
        );

        style.setFillForegroundColor((short) 9);
        style.setFillPattern((short) 1);
        //style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setFont(titleFont);
        styleMap.put(excelCellStyle.getBgColor(), style);
        return style;
    }
    private int convertHexToNumber(String hex) {
        int num = 0;
        try {
            num = Integer.parseInt(hex, 16);
        } catch (Throwable t) {
            logger.error("數字轉換異常 " + t);
        }
        return num;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章