ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] # 1. 使用POI提供的颜色 ```java //获取样式对象 CellStyle cellStyle = workbook.createCellStyle(); //设置颜色样式 cellStyle.setFillBackgroundColor(IndexedColors.BRIGHT_GREEN.getIndex()); cellStyle.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex()); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); SXSSFRow row = sheet.createRow(i + 1); SXSSFCell cell = row.createCell(0); //将样式用到单元格中 cell.setCellStyle(cellStyle); ``` 设置单元格背景颜色如下: ![](https://img.kancloud.cn/dc/c1/dcc15b5b2fdc971a321091fa3e705c00_1519x172.png) <br/> # 2. 自定义颜色 HSSF与XSSF、SXSSF自定义颜色的方式有所不同。 <br/> **1. HSSF自定义颜色** ```java //创建文档对象 HSSFWorkbook workbook = new HSSFWorkbook(); //获取HSSFPalette HSSFPalette palette = workbook.getCustomPalette(); //将 IndexedColors.BRIGHT_GREEN.getIndex() 所代表的颜色重写为 (byte) 0, (byte) 176, (byte) 80 颜色 palette.setColorAtIndex(IndexedColors.BRIGHT_GREEN.getIndex(), (byte) 0, (byte) 176, (byte) 80); //设置颜色样式 CellStyle cellStyle = workbook.createCellStyle(); //调用 IndexedColors.BRIGHT_GREEN.getIndex() cellStyle.setFillBackgroundColor(IndexedColors.BRIGHT_GREEN.getIndex()); cellStyle.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex()); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); HSSFRow row = sheet.createRow(i + 1); HSSFCell cell = row.createCell(2); //将样式用到单元格中 cell.setCellStyle(cellStyle); ``` 自定义的颜色如下: ![](https://img.kancloud.cn/1d/a0/1da06c8c69de82a307d6879603090f3b_1592x162.png) <br/> **2. XSSF、SXSSF自定义颜色** ```java SXSSFWorkbook workbook = new SXSSFWorkbook(); ... //自定义颜色 XSSFColor xssfColor = new XSSFColor(new java.awt.Color(0, 176, 80), new DefaultIndexedColorMap()); //设置背景颜色样式 XSSFCellStyle cellStyle = (XSSFCellStyle) workbook.createCellStyle(); cellStyle.setFillBackgroundColor(xssfColor); cellStyle.setFillForegroundColor(xssfColor); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); ... SXSSFCell genderCell = row.createCell(2); //设置单元格样式 genderCell.setCellStyle(cellStyle); ... ``` 自定义的颜色如下: ![](https://img.kancloud.cn/1d/a0/1da06c8c69de82a307d6879603090f3b_1592x162.png)