设置自定义颜色取决于
Excel文件的类型(Office Open XML格式
*.xlsx与BIFF格式
*.xls)。
apachepoi由于弃用,使用不同版本的可能会有所不同。
使用Office Open
XML格式,
*.xlsx我们可以简单地使用XSSFColor的构造函数设置新颜色。在
apachepoi 4.0.0
XSSFColor(byte[] rgb, IndexedColorMapcolorMap)可以使用。
IndexedColorMap可
null如果没有其他颜色的地图应使用而不是默认的一个。
使用BIFF格式时,
*.xls只能使用索引颜色。但是可能会临时覆盖某些索引颜色。
以下代码显示了两者都用于设置单元格的填充颜色。使用的自定义颜色是RGB(112,134,156)。使用
HSSF(BIFF格式
*.xls)索引颜色
HSSFColor.HSSFColorPredefined.LIME将被暂时覆盖。
请注意,以下内容已通过测试并可以使用
apache poi 4.0.0。不保证使用其他版本。
import java.io.FileOutputStream;import org.apache.poi.ss.usermodel.*;import org.apache.poi.xssf.usermodel.*;import org.apache.poi.hssf.usermodel.*;import org.apache.poi.hssf.util.HSSFColor;public class CreateExcelCustomColor { public static void main(String[] args) throws Exception { Workbook workbook = new XSSFWorkbook(); //Workbook workbook = new HSSFWorkbook(); CellStyle cellcolorstyle = workbook.createCellStyle(); cellcolorstyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); byte[] rgb = new byte[]{(byte)112, (byte)134, (byte)156}; if (cellcolorstyle instanceof XSSFCellStyle) { XSSFCellStyle xssfcellcolorstyle = (XSSFCellStyle)cellcolorstyle; xssfcellcolorstyle.setFillForegroundColor(new XSSFColor(rgb, null)); } else if (cellcolorstyle instanceof HSSFCellStyle) { cellcolorstyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIME.getIndex()); HSSFWorkbook hssfworkbook = (HSSFWorkbook)workbook; HSSFPalette palette = hssfworkbook.getCustomPalette(); palette.setColorAtIndex(HSSFColor.HSSFColorPredefined.LIME.getIndex(), rgb[0], rgb[1], rgb[2]); } Sheet sheet = workbook.createSheet(); Cell cell = sheet.createRow(0).createCell(0); cell.setCellStyle(cellcolorstyle); FileOutputStream out = null; if (workbook instanceof XSSFWorkbook) { out = new FileOutputStream("CreateExcelCustomColor.xlsx"); } else if (workbook instanceof HSSFWorkbook) { out = new FileOutputStream("CreateExcelCustomColor.xls"); } workbook.write(out); out.close(); workbook.close(); }}


