easyexcel多级表头导出各级设置样式(继承HorizontalCellStyleStrategy实现)
java
package com.example.wxmessage.entity;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
/**
* @author chenyuhuan
* @ClassName CellStyleStrategy.java
* @Description TODO
* @createTime 2023年12月01日
*/
public class CellStyleStrategy extends HorizontalCellStyleStrategy {
private final WriteCellStyle headWriteCellStyle;
public CellStyleStrategy(WriteCellStyle headWriteCellStyle) {
this.headWriteCellStyle = headWriteCellStyle;
}
@Override
protected void setHeadCellStyle(CellWriteHandlerContext context) {
// 根据行索引为不同级别的表头应用不同样式
if (context.getRowIndex() == 0) {
headWriteCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
} else if (context.getRowIndex() == 1) {
headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
}
if (stopProcessing(context)) {
return;
}
WriteCellData<?> cellData = context.getFirstCellData();
WriteCellStyle.merge(this.headWriteCellStyle, cellData.getOrCreateStyle());
}
}
###########################调用###############################
EasyExcel.write(response.getOutputStream(), ParamWorkdaysExportExcel.class)
.registerWriteHandler(new CellStyleStrategy(new WriteCellStyle()))
.sheet("模板")
.doWrite(data);