原文链接出自:easyExcel设置单个单元格(颜色)样式

背景:需求是使用excel设置目标单元格的样式(颜色),但我之前没有学过easyExcel,在网上找资料的时候,发现有关easyExcel相关的单个单元格样式设置的资料比较少,有的还源码不全,只能说用来参考。我的代码很多一部分是借鉴这个博客的https://blog.csdn.net/abc20090208/article/details/89054599,但他没有设置颜色,需要设置颜色还需要找其他的资料。其中相关的颜色说明的链接为:https://blog.csdn.net/z1074907546/article/details/50544178。

进一步说明,需要设置单个单元格需要Workbook,但阿里提供的接口比较局限,在很多地方访问只能使用反射的方法,在这里并没有提供反射的使用方法。我在下一篇讲使用java自带的security包解码x509的字符串的时候会使用反射,有兴趣可以看看。链接是:使用java自带的sercurity包解析x.509证书字符串_cannot access class sun.security.x509.x509certinfo_短腿哥哥的博客-CSDN博客

相关代码如下(注释比较多,我就不细讲了,有问题留言~):

<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>1.1.2-beta5</version></dependency>
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;/*** https://blog.csdn.net/abc20090208/article/details/89054599  阿里开源Easy-Excel单元格样式调整** @ExcelProperty注解是用来标记字段在Excel中的表头,value值支持多级表头,用一级表头一致框架* 自动会对表头进行合并index是用来标记在Excel中的顺序(不是Excel中的位置),因为项目实际需要中有几个字段是可选* 导出的,所以index没有设置成连续的,其次导出的字段中总量要求有千分位分隔符,两个满足率字段要求有百分号,因此* 需要单独设置单元格的样式。**/
public class BasePurchaseExecutionResponse extends BaseRowModel {/*** 序号*/@ExcelProperty(value = {"", "", "序号"}, index = 0)private String num;/*** 供应商类型*/@ExcelProperty(value = {"", "", "供应商类型"}, index = 1)private String supplierType;/*** 品牌*/@ExcelProperty(value = {"", "", "品牌"}, index = 2)private String brandNameListString;/*** 年份*/@ExcelProperty(value = {"", "", "年份"}, index = 3)private String productYear;/*** 产品季节*/@ExcelProperty(value = {"", "", "产品季节"}, index = 4)private String productSeason;/*** 总量*/@ExcelProperty(value = {"", "", "总量"}, index = 9)private int totalShipment;/*** 计划交期满足率*/@ExcelProperty(value = {"", "", "计划交期满足率"}, index = 10)private String planDeliverRate;/*** 确认交期满足率*/@ExcelProperty(value = {"", "", "确认交期满足率"}, index = 11)private String confirmDeliverRate;public String getNum() {return num;}public void setNum(String num) {this.num = num;}public String getSupplierType() {return supplierType;}public void setSupplierType(String supplierType) {this.supplierType = supplierType;}public String getBrandNameListString() {return brandNameListString;}public void setBrandNameListString(String brandNameListString) {this.brandNameListString = brandNameListString;}public String getProductYear() {return productYear;}public void setProductYear(String productYear) {this.productYear = productYear;}public String getProductSeason() {return productSeason;}public void setProductSeason(String productSeason) {this.productSeason = productSeason;}public int getTotalShipment() {return totalShipment;}public void setTotalShipment(int totalShipment) {this.totalShipment = totalShipment;}public String getPlanDeliverRate() {return planDeliverRate;}public void setPlanDeliverRate(String planDeliverRate) {this.planDeliverRate = planDeliverRate;}public String getConfirmDeliverRate() {return confirmDeliverRate;}public void setConfirmDeliverRate(String confirmDeliverRate) {this.confirmDeliverRate = confirmDeliverRate;}
}
import com.alibaba.excel.event.WriteHandler;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;import java.math.BigDecimal;/*** @author Eric on 2019/4/5.* @version 1.0*/
public class StyleExcelHandler implements WriteHandler {private static int time=0;@Overridepublic void sheet(int i, Sheet sheet) {}@Overridepublic void row(int i, Row row) {}@Overridepublic void cell(int i, Cell cell) {// 从第二行开始设置格式,第一行是表头//这里可以获得Workbook是因为Sheet类有这个接口,但是其他地方没有对应的Sheet,所以要获得的话,需要用到反射了Workbook workbook = cell.getSheet().getWorkbook();CellStyle cellStyle = createStyle(workbook);if (cell.getRowIndex() > 2) {if (i == 5) {DataFormat dataFormat = workbook.createDataFormat();// 设置千位分隔符cellStyle.setDataFormat(dataFormat.getFormat("#,##0"));time++;if(time==2){//这个终于可以设置颜色了  https://blog.csdn.net/z1074907546/article/details/50544178 这个链接有颜色说明。//setFillPattern是设置单元格填充样式,SOLID_FOREGROUND纯色使用前景颜色填充,接着设置前景颜色// (setFillForegroundColor)就可以给单元格着色了。setFillForegroundColor()方法的参数是一个short类型,// easyExcel使用索引来代表颜色,默认已经有一些颜色了。可以自定义颜色,可以自定义颜色,可以自定义颜色。cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);//设置前景填充样式cellStyle.setFillForegroundColor(HSSFColor.DARK_RED.index);//前景填充色//cellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());}}if (i == 7 || i == 6) {String stringCellValue = cell.getStringCellValue();cell.setCellValue(new BigDecimal(stringCellValue.replaceAll("%", "")).divide(new BigDecimal(100), 8, BigDecimal.ROUND_HALF_UP).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());// 设置百分比cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00%"));}if (i == 0 || i == 3) {cell.setCellValue(Long.parseLong(cell.getStringCellValue()));}}cell.getRow().getCell(i).setCellStyle(cellStyle);}/*** 实际中如果直接获取原单元格的样式进行修改, 最后发现是改了整行的样式, 因此这里是新建一个样* 式*/private CellStyle createStyle(Workbook workbook) {CellStyle cellStyle = workbook.createCellStyle();// 下边框cellStyle.setBorderBottom(BorderStyle.THIN);// 左边框cellStyle.setBorderLeft(BorderStyle.THIN);// 上边框cellStyle.setBorderTop(BorderStyle.THIN);// 右边框cellStyle.setBorderRight(BorderStyle.THIN);// 水平对齐方式cellStyle.setAlignment(HorizontalAlignment.CENTER);//cellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());// 垂直对齐方式cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);return cellStyle;}
}
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;import org.junit.jupiter.api.Test;import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** easyExcel不足之处:*     样式的设置可维护性太差,通过在样式类中硬编码各个列号对应的样式确实不太好,问题点在于,单元格样式的创建需要*     workBook对象实例才可以,框架本身并没有提供获取wirkBook的方法,因此,如果想要在其他地方设置样式的话,可以*     通过反射的方式来获取workbook对象*/
public class test3 {public static void main(String[] args) throws IOException {StyleExcelHandler handler = new StyleExcelHandler();OutputStream outputStream = new FileOutputStream("D://2007.xlsx");// 这里要把上面创建的样式类通过构造函数传入ExcelWriter writer = new ExcelWriter(null, outputStream, ExcelTypeEnum.XLSX, true, handler);Sheet sheet1 = new Sheet(1, 1, BasePurchaseExecutionResponse.class, "含供应商和地区", null);//设置列宽 设置每列的宽度Map columnWidth = new HashMap();columnWidth.put(0,10000);columnWidth.put(1,10000);columnWidth.put(2,10000);columnWidth.put(3,10000);sheet1.setColumnWidthMap(columnWidth);//或自适应宽度//sheet1.setAutoWidth(true);writer.write(createResponseList(), sheet1);writer.finish();outputStream.close();}/*** 创建数据集合** @return*/private static List<? extends BaseRowModel> createResponseList() {List<BasePurchaseExecutionResponse> responses = new ArrayList<>();for (int i = 1; i <= 10; i++) {BasePurchaseExecutionResponse response = new BasePurchaseExecutionResponse();response.setTotalShipment(i * 1000000);response.setConfirmDeliverRate( i+ "%");response.setNum(String.valueOf(i));response.setProductSeason("冬收到甲方");response.setProductYear("19");response.setSupplierType("本厂");response.setBrandNameListString("耐特");response.setPlanDeliverRate(i * 2 + "%");responses.add(response);}return responses;}
}

EasyExcel设置特定单个单元格(颜色)样式相关推荐

  1. easyExcel设置单个单元格(颜色)样式

    背景:需求是使用excel设置目标单元格的样式(颜色),但我之前没有学过easyExcel,在网上找资料的时候,发现有关easyExcel相关的单个单元格样式设置的资料比较少,有的还源码不全,只能说用 ...

  2. EasyExcel设置行中单个单元格的样式

    1. 前言 在近期的工作中遇到一个导出Excel的需求: 用户通过Excel导入信息,校验用户导入的信息是否合法:如果导入的信息不合法,则保存失败:并且需要精确到行的字段设置标识,然后再将用户导入的信 ...

  3. POI设置单个单元格的样式

    一.POI的基础样式 1. 单元格样式 CellStyle决定了单元格的显示样式,决定了单元格: - 单元格各个边框样式及颜色- 单元格填充图案.前景色及背景色- 单元格内容水平.垂直对齐方式- 单元 ...

  4. element-ui 设置table表格单元格背景样式

    在table表格绑定call-style属性,声明一个方法就可以设置样式了: <el-table border stripe height="76vh" v-loading= ...

  5. Vue+iview表格如何给单个单元格设置样式

    官方文档地址:https://www.iviewui.com/components/table#TDYS,单元格:通过给数据 data 设置字段 cellClassName 可以给任意一个单元格指定样 ...

  6. EasyExcel v2.1.6单元格样式设置

    EasyExcel v2.1.6单元格样式设置 1.实体类代码 2.注解类 3.自定义注解类实现 4.导出Excel文件实现类 使用AlibabaEasyExcel v2.1.6导出excel文件,的 ...

  7. hutool工具ExcelWriter设置单个单元格样式

    官网自定义样式: ExcelWriter writer = ...;// 定义单元格背景色 StyleSet style = writer.getStyleSet(); // 第二个参数表示是否也设置 ...

  8. Excel生成报表之解决方案--设置单个单元格格式

    首先要看效果图: 单元格C3设置字体.数据格式和边框属性,要生成这样的效果要进行哪些设置.先看在微软Excel中如何需要设置. 一.微软Excel中设置单个单元格 1.首先在C3中输入数值12. 如果 ...

  9. java excel单元格背景色,『excel表格尺寸设置』Java如何设置被导出excel单元格的样式?比如背景色,大小什么的?...

    Java如何设置被导出excel单元格的样式?比如背景色,大小什么的? 使 poi ,具体实现 HSSFCellStyle style = null; // 创建表头style HSSFCellSty ...

最新文章

  1. 暑期集训2:ACM基础算法 练习题A:CF-1008C
  2. 建立Microsoft SQL Server 2005数据仓库
  3. 在eclipse中创建web项目(非myeclipse)
  4. 戴尔笔记本win8全新安装
  5. Stack around the variable 'date' was corrupted.
  6. excel找出重复值
  7. 三/五/七/九点二次平滑法
  8. 2021年高处安装、维护、拆除考试试卷及高处安装、维护、拆除操作证考试
  9. HTML5期末大作业:动物主题网站设计——酷酷动物主题响应式网页(5页) 大学生动物主题网页作品 动物网页设计作业模板 学生网页制作源代码下载
  10. 关于外国人报考美国专利代理人的基础介绍
  11. 备份数据库、恢复数据库
  12. 分布式系统设计模式,你用过哪些?
  13. android基础知识13:AndroidManifest.xml文件解析【转载】
  14. Nginx+Tomcat实现负载均衡与动静分离
  15. android开发获取应用本身耗电量_近期值得关注的 iOS、Android 和 PC App
  16. 微信小程序手机软键盘距离input输入框位置
  17. python装饰器与闭包---装饰器
  18. 腹直肌整体(03):悬垂提臀抬腿
  19. “智慧交通”能否为治理城市拥堵开出新“药方”?
  20. 解读订阅号和服务号的区别

热门文章

  1. 北京科技大学计算机学硕难度,大家好,请问北京科技大学的电子信息专业怎么样?考研的话相对来说难吗?进复试的话差不多得多少分...
  2. Qt “error: C2065: “xxx”: 未声明的标识符”的问题
  3. 自由枪骑兵修改服务器端口,自由枪骑兵 Freelancer 更改高分辨率(支持宽屏)方法...
  4. 你的背景调查值多少钱?
  5. 灰色关联度分析(python)
  6. RF基础(相位和波长、回波损耗和驻波比、电缆阻抗、极化、天线波束宽度)
  7. 【sql server】回车换行符的替代
  8. 远行星号java 出错_按照教程搞了一条新船,但是出错了,求大神看看怎么回事...
  9. C语言基础 - 20230501
  10. 怎么改图片大小格式?如何更改图片的尺寸?