1. 程式人生 > 其它 >POI顯示Excel表格具體配置顏色

POI顯示Excel表格具體配置顏色

public static void main(String[] args)   {
    short colorNum = 2;//每行顯示的顏色的個數
    short width1 = 2000;//顏色序寬度
    short width = 6000;//顏色名欄位的寬度
    XSSFWorkbook workbook = new XSSFWorkbook();
    CellStyle thStyle = workbook.createCellStyle();

    XSSFSheet sheet = workbook.createSheet("IndexedColors遍歷");
    Row row =null;
    Cell cell;
    short i,j,index=0;
    String text="";
    for(i=0;i<colorNum;i++){
        sheet.setColumnWidth((short) i*3 , width1 );
        sheet.setColumnWidth((short) i*3 + 1 , width );
    }
    for (IndexedColors c : IndexedColors.values()){
        i=(short) (index/colorNum);
        j=(short) (index%colorNum);
        thStyle = workbook.createCellStyle();
        thStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);  //設定前景填充樣式
        thStyle.setFillForegroundColor(c.getIndex());
        row = j==0?sheet.createRow(i):row;//如果到了換行的時候row new一下 否則就當什麼都沒有發生
        row.createCell(3*j).setCellValue("  "+(c.getIndex() + 1000 + "").substring(1,4));
        row.createCell(3*j+1).setCellValue(c+"");
        row.createCell(3*j+2).setCellStyle(thStyle);
        index++;//計數
    }

    sheet = workbook.createSheet("30X"+colorNum+"顏色遍歷");

    for( i=0;i<30;i++ ){
        row = sheet.createRow(i);
        for(j=0;j<colorNum;j++){
            thStyle = workbook.createCellStyle();
            thStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);  //設定前景填充樣式
            int size =(colorNum*i + j);
            thStyle.setFillForegroundColor((short)size);
            row.createCell(2*j).setCellValue((short)size);
            row.createCell(2*j+1).setCellStyle(thStyle);
        }
    }

    FileOutputStream fileOut = null;
    try {
        fileOut = new FileOutputStream("D:/POI顏色大全.xlsx");
        workbook.write(fileOut);
        fileOut.close();
    } catch (Exception e) {
        System.out.println("儲存xlsx的時候發生的異常");
        e.printStackTrace();
    }
}