Java中对POI的单元格设置背景色
生活随笔
收集整理的這篇文章主要介紹了
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的单元格设置背景色的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java的poi的excel导入怎么判断
- 下一篇: MyBatisPlus中全局Sql注入器