public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\px\\Desktop\\xxx.xls");
backgroundColor(file,"200306-006954-00",2,0, 255,0,0);
}
/**
* 针对单个单元格设置背景色
* @param file 文件
* @param sheetName sheet名
* @param rownum 列号
* @param column 行号
* @param red 颜色R值
* @param green 颜色G值
* @param blue 颜色B值
* @throws Exception
*/
public static void backgroundColor(File file, String sheetName, int rownum,int column,int red, int green, int blue) throws Exception {
FileInputStream exlFile = new FileInputStream(file);
// POI给出的解决兼容Excel 2003和2007以上版本的方法
Workbook workbook = WorkbookFactory.create(exlFile);
if (workbook instanceof HSSFWorkbook) {
HSSFWorkbook workbook2 = (HSSFWorkbook) workbook;
backgroundColorHSSF(workbook2,workbook2.getSheet(sheetName),rownum,column,(byte) red,(byte)green,(byte)blue);
} else if (workbook instanceof XSSFWorkbook) {
XSSFWorkbook workbook2 = (XSSFWorkbook) workbook;
backgroundColorXSSF(workbook2,workbook2.getSheet(sheetName),rownum,column,red,green,blue);
}
exlFile.close();// 关闭文件输入流
FileOutputStream fos = new FileOutputStream(file);
workbook.write(fos);
fos.close();// 关闭文件输出流
}
/**
* 设置背景色
* @param workbook
* @param sheet
* @param rownum
* @param column
* @param red
* @param green
* @param blue
*/
public static void backgroundColorHSSF(HSSFWorkbook workbook,HSSFSheet sheet,int rownum,int column,byte red, byte green, byte blue){
HSSFPalette palette02 = workbook.getCustomPalette();
palette02.setColorAtIndex((short) 10, red, green, blue);
HSSFColor color02 = palette02.findColor(red, green, blue);
HSSFCell cell = sheet.getRow(rownum).getCell(column);
HSSFCellStyle style = cell.getCellStyle();
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.cloneStyleFrom(style);
cellStyle.setFillForegroundColor(color02.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(cellStyle);
}
/**
* 设置背景色
* @param workbook
* @param sheet
* @param rownum
* @param column
* @param red
* @param green
* @param blue
*/
public static void backgroundColorXSSF(XSSFWorkbook workbook,XSSFSheet sheet,int rownum,int column,int red, int green, int blue){
XSSFCell cell = sheet.getRow(rownum).getCell(column);
XSSFCellStyle style = cell.getCellStyle();
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.cloneStyleFrom(style);
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 设置填充方案
cellStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(red,green,blue))); // 设置填充颜色
cell.setCellStyle(cellStyle);
}