欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > java >内容正文

java

Java中对POI的单元格设置背景色

发布时间:2025/3/19 java 46 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Java中对POI的单元格设置背景色 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

场景

SpringBoot中使用POI实现Excel导入到数据库(图文教程已实践):

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/88660466

需求

在进行导入时,在导入数据库之前需要进行格式的验证,格式不正确则将单元格背景色设置为红色。

实现

主要实现代码

CellStyle style =  workbook.createCellStyle();style.setFillForegroundColor(IndexedColors.RED.getIndex());style.setFillPattern(CellStyle.SOLID_FOREGROUND);deliveryTimeCell.setCellStyle(style);

 

示例代码

Workbook workbook = null; //获取文件格式 String fileType = path.substring(path.lastIndexOf(".") + 1, path.length()); InputStream stream = new FileInputStream(path); //如果后缀名为xls,使用HSSF if (fileType.equals("xls")) {workbook = new HSSFWorkbook(stream);//如果后缀名是xlsx,使用XSSF}else if (fileType.equals("xlsx")){workbook = new XSSFWorkbook(stream);} Sheet sheet= workbook.getSheet("sheet1"); //获取行数 int rows=sheet.getPhysicalNumberOfRows(); //获取第二行数据 Row row2 =sheet.getRow(1); if(row2!=null){ //日期格式加校验 Cell deliveryTimeCell = row2.getCell(3); if(deliveryTimeCell!=null){ //如果是数值类型if(deliveryTimeCell.getCellType()==0){if(HSSFDateUtil.isCellDateFormatted(deliveryTimeCell)){//获取送货日期Date deliveryTime =deliveryTimeCell.getDateCellValue();receiveOrder.setDeliveryTime(deliveryTime);}else{//设置送货时间为红色CellStyle style =  workbook.createCellStyle();style.setFillForegroundColor(IndexedColors.RED.getIndex());style.setFillPattern(CellStyle.SOLID_FOREGROUND);deliveryTimeCell.setCellStyle(style);isValidatePass=false;}}else{//设置送货时间为红色CellStyle style =  workbook.createCellStyle();style.setFillForegroundColor(IndexedColors.RED.getIndex());style.setFillPattern(CellStyle.SOLID_FOREGROUND);deliveryTimeCell.setCellStyle(style);isValidatePass=false;} }

 

输出设置后的excel

FileOutputStream fileOut = new FileOutputStream(path);workbook.write(fileOut);fileOut.close();

示例效果

颜色参照表

与50位技术专家面对面20年技术见证,附赠技术全景图

总结

以上是生活随笔为你收集整理的Java中对POI的单元格设置背景色的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。