ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

用java-poi为Excel设置好看的颜色

2022-04-26 18:33:51  阅读:378  来源: 互联网

标签:cellStyle java wb Excel style THIN poi sheet font


写个工具将所有颜色代码的实际效果生成出来

 1 static void colorTest() throws IOException {
 2         Workbook wb = new HSSFWorkbook();
 3         Sheet sheet = wb.createSheet("colorful");
 4         int rowNum = 0;
 5         for (IndexedColors color : IndexedColors.values()) {
 6             Row row = sheet.createRow(rowNum++);
 7             Cell cell = row.createCell(0);
 8             cell.setCellValue(color.toString());
 9             Cell cellColor = row.createCell(1);
10             CellStyle style = wb.createCellStyle();
11             style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
12             style.setFillForegroundColor(color.getIndex());
13             cellColor.setCellStyle(style);
14         }
15         sheet.setColumnWidth(0,25*256);
16         sheet.setColumnWidth(1,50*256);
17         FileOutputStream fout = new FileOutputStream(new File("d:\\colors.xls"));
18         wb.write(fout);
19         wb.close();
20         fout.close();
21     }

生成结果:

 

 

实际使用:

cellStyle.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); //单元格背景色
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);//前景填充模式

 

其他常用Excel样式设置:

cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中

cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
cellStyle.setBorderTop(BorderStyle.THIN);//上边框
cellStyle.setBorderRight(BorderStyle.THIN);//右边框

HSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short)9);//字体大小
font.setFontName("微软雅黑");//字体
font.setBold(true); //加粗
font.setColor(Font.COLOR_NORMAL); //字体颜色
cellStyle.setFont(font);

cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00%")); //设置数字以百分比显示

 

标签:cellStyle,java,wb,Excel,style,THIN,poi,sheet,font
来源: https://www.cnblogs.com/sen-2017/p/16195951.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有