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_style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN1.index); //自定义字体颜色, 同单元格样式 HSSFFont font = workbook.createFont(); font.setFontHeightInPoints((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单元格样式的问题,谨记录一波!