java poi导出excel单元格设置自定义背景颜色(任意颜色)

转自:http://t.csdn.cn/QHfUU

// 创建一个 workbook 对象 
Workbook workbook = new XSSFWorkbook();
// 创建一个 sheet对象
Sheet sheet = workbook.createSheet();
//创建一行对象
Row row = sheet.createRow((short) 1);
//获取样式对象
XSSFCellStyle = workbook.createCellStyle();
//自定义颜色对象
XSSFColor color = new XSSFColor();
//根据你需要的rgb值获取byte数组
color.setRGB(intToByteArray(getIntFromColor(255,255,255)));
//自定义颜色
style.setFillForegroundColor(color);
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
Cell cell = row.createCell((short) 1);
cell.setCellValue("X1");
cell.setCellStyle(style);

/**
* rgb转int
*/
private static int getIntFromColor(int Red, int Green, int Blue){
    Red = (Red << 16) & 0x00FF0000;
    Green = (Green << 8) & 0x0000FF00;
    Blue = Blue & 0x000000FF;
    return 0xFF000000 | Red | Green | Blue;
}

/**
 * int转byte[]
 */
public static byte[] intToByteArray(int i) {
    byte[] result = new byte[4];
    result[0] = (byte)((i >> 24) & 0xFF);
    result[1] = (byte)((i >> 16) & 0xFF);
    result[2] = (byte)((i >> 8) & 0xFF);
    result[3] = (byte)(i & 0xFF);
    return result;
}

 

posted @ 2022-11-15 13:51  moonsoft  阅读(3554)  评论(0编辑  收藏  举报