背景:需求是使用excel设置目标单元格的样式(颜色),但我之前没有学过easyExcel,在网上找资料的时候,发现有关easyExcel相关的单个单元格样式设置的资料比较少,有的还源码不全,只能说用来参考。我的代码很多一部分是借鉴这个博客的https://blog.csdn.net/abc20090208/article/details/89054599,但他没有设置颜色,需要设置颜色还需要找其他的资料。其中相关的颜色说明的链接为:https://blog.csdn.net/z1074907546/article/details/50544178。
进一步说明,需要设置单个单元格需要Workbook,但阿里提供的接口比较局限,在很多地方访问只能使用反射的方法,在这里并没有提供反射的使用方法。我在下一篇讲使用java自带的security包解码x509的字符串的时候会使用反射,有兴趣可以看看。链接是:https://blog.csdn.net/lxh123456789asd/article/details/97407254
相关代码如下(注释比较多,我就不细讲了,有问题留言~):
<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;
@Override
public void sheet(int i, Sheet sheet) {
}
@Override
public void row(int i, Row row) {
}
@Override
public 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;
}
}