1. 程式人生 > >POI 設定單元格樣式

POI 設定單元格樣式

public static void writeExcel(List<ServAuthBean> data_list){
		//新建工作簿
		HSSFWorkbook workbook = new HSSFWorkbook();
		
		//自定義顏色
		HSSFPalette palette = workbook.getCustomPalette();
		//十六進位制顏色RGB碼
		String color = "99CC00";
		//將十六進位制碼轉為十進位制數字
		int r = Integer.parseInt(color.substring(0, 2), 16);
		int g = Integer.parseInt(color.substring(2, 4), 16);
		int b = Integer.parseInt(color.substring(4, 6), 16);
		//自定義索引顏色
		palette.setColorAtIndex((short)9, (byte)r, (byte)g, (byte)b);
//建立單元格樣式 HSSFCellStyle cell_style = workbook.createCellStyle(); //此處將HSSFCellStyle.SOLID_FOREGROUND改為FillPatternType.SOLID_FOREGROUND,網上搜索資料一堆錯誤用法 cell_style.setFillPattern(FillPatternType.SOLID_FOREGROUND); cell_style.setAlignment(HorizontalAlignment.CENTER); cell_style.setFillForegroundColor((short)9); //以下為API自帶的顏色設定 // cell_sytle.setFillForegroundColor(IndexedColors.BRIGHT_GREEN1.index); //自定義字型顏色, 同單元格樣式 HSSFFont font = workbook.createFont(); font.setFontHeight((short)9); //字型設定為Arial font.setFontName(HSSFFont.FONT_ARIAL); //設定索引 10 為白色 palette.setColorAtIndex((short)10, (byte) 255, (byte) 255, (byte) 255); //將字型顏色設為白色 font.setColor((short)9); cell_style.setFont(font); //建立sheet表格 HSSFSheet sheet = workbook.createSheet("ServAuth"); //設定單元格列寬 sheet.setColumnWidth(1, 50*100); sheet.setColumnWidth(2, 50*100); sheet.setColumnWidth(3, 50*100); // 建立報文頭第一行 HSSFRow row_0 = sheet.createRow(0); HSSFCell cell0 = row_0.createCell(0); // 資料域個數 cell0.setCellValue("資料域個數"); cell0.setCellStyle(cell_style); // 第二行賦值操作 HSSFRow row_1 = sheet.createRow(1); row_1.createCell(0).setCellValue(10); // 第三行賦值 HSSFRow row_2 = sheet.createRow(2); HSSFCell cell_2_0 = row_2.createCell(0); cell_2_0.setCellValue("服務編號"); cell_2_0.setCellStyle(cell_style); HSSFCell cell_2_1 = row_2.createCell(1); cell_2_1.setCellValue("服務請求方程式碼"); cell_2_1.setCellStyle(cell_style); HSSFCell cell_2_2 = row_2.createCell(2); cell_2_2.setCellValue("授權標誌"); cell_2_2.setCellStyle(cell_style); // 第四行往後用查詢資料填充 int row_num = 3; for (ServAuthBean data_bean : data_list) { HSSFRow row = sheet.createRow(row_num); row.createCell(0).setCellValue(data_bean.getServ_id()); row.createCell(1).setCellValue(data_bean.getApps_sys_id()); row.createCell(2).setCellValue(data_bean.getStatus()); row_num++; } //檔名 String file_name = "授權.xls"; FileOutputStream fos = null; try { fos = new FileOutputStream(file_name); try { workbook.write(fos); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { if(workbook != null) { workbook.close(); } if(fos != null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } } }

 最近專案遇到用POI匯出檔案,碰到關於excel單元格樣式的問題,謹記錄一波!