使用pio修改excel表格單元格自定義背景色

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);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章