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();

示例效果

颜色参照表

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值