700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Java Excel导出动态自定义单元格样式

Java Excel导出动态自定义单元格样式

时间:2020-05-20 04:12:13

相关推荐

Java Excel导出动态自定义单元格样式

根据表格内容定义单元格样式

效果图:

文章描述两种,一种创建生成时定义样式,另一种在excel在写入文件前修改样式

关键代码一

/*** 数据动态设置样式** @param cell 单元格* @param value 单元格数据*/private void getStyleColor(Cell cell, Object value) {if (!ObjectUtils.isEmpty(value)) {Double aDouble;try {aDouble = Double.valueOf(value.toString());} catch (Exception e) {return;}short colorIndex; // 颜色下标// 判断分数大小 动态赋值样式if (aDouble < 60) {colorIndex = IndexedColors.RED.getIndex();} else if (aDouble >= 60 && aDouble < 80) {colorIndex = IndexedColors.GREEN.getIndex();} else {colorIndex = IndexedColors.BLACK.getIndex();}CellStyle cellStyle1 = wb.createCellStyle(); // 创建样式cellStyle1.cloneStyleFrom(cell.getCellStyle()); // 克隆原先样式Font font = wb.createFont(); // 创建字体font.setColor(colorIndex);cellStyle1.setFont(font);// 设置样式cell.setCellStyle(cellStyle1);}}

关键代码二

/*** 表格创建后未写入前,修改样式*/private void styleColorCustom() {// 取出生成好的表格页Sheet sheetAt = wb.getSheetAt(0);// 开始遍历数据for (Row cells : sheetAt) {for (Cell cell : cells) {// 创建样式CellStyle newCellStyle = wb.createCellStyle();newCellStyle.cloneStyleFrom(cell.getCellStyle()); // 克隆原先样式String stringCellValue = cell.getStringCellValue(); // 获取单元格数据Double aDouble;try {aDouble = Double.parseDouble(stringCellValue);} catch (Exception e) {continue;}short colorIndex;// 根据数据判断赋值if (aDouble < 60) {colorIndex = IndexedColors.RED.getIndex();} else if (aDouble >= 60 && aDouble < 80) {colorIndex = IndexedColors.GREEN.getIndex();} else {colorIndex = IndexedColors.BLACK.getIndex();}newCellStyle.setFont(getFont(wb, (short) 10, false, colorIndex));cell.setCellStyle(newCellStyle); // 设置新样式}}}/*** 获取字体样式* @param workbook* @param size* @param isBold* @param colorIndex* @return*/private Font getFont(Workbook workbook, short size, boolean isBold, short colorIndex) {Font font = workbook.createFont();font.setFontName("Arial"); // 字体样式font.setBold(isBold); // 是否加粗font.setFontHeightInPoints(size); // 字体大小font.setColor(colorIndex);return font;}

使用的 apachePoi,文章只展示关键修改方式代码

颜色、编码对照 (/article/3391.html)

地址:/article/3391.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。