需求背景:需要导出的excel为两个sheet页,并且对表头的样式做特殊设置
1.具体代码
public byte[] writeGoodsFieldsTemplate(Map<String,List<String>> goodsFieldsHeader,ExportTaskDto exportTaskDto) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
// 必填字段红色
WriteCellStyle requiredCellStyle = new WriteCellStyle();
WriteFont headWriteFont1 = new WriteFont();
headWriteFont1.setColor(IndexedColors.RED.getIndex());
requiredCellStyle.setWriteFont(headWriteFont1);
// 非必填字段黑色
WriteCellStyle notRequiredCellStyle = new WriteCellStyle();
WriteFont headWriteFont2 = new WriteFont();
headWriteFont2.setColor(IndexedColors.BLACK.getIndex());
notRequiredCellStyle.setWriteFont(headWriteFont2);
// 合并表头
List<List<String>> mergedHead = new ArrayList<>();
mergedHead.addAll(convertHead(goodsFieldsHeader.get("required")));
mergedHead.addAll(convertHead(goodsFieldsHeader.get("notRequired")));
// 商品资料sheet页
WriteSheet productInformationSheet = EasyExcel.writerSheet("商品资料").
head(mergedHead)
.registerWriteHandler(new GoodsFieldsWriteHandler(requiredCellStyle,notRequiredCellStyle,goodsFieldsHeader.get("required").size()))
.build();
excelWriter.write(Collections.emptyList(),productInformationSheet);
// 字段定义说明Sheet页
WriteSheet fieldsDescribeSheet = EasyExcel.writerSheet("字段定义说明").head(exportTaskDto.getClazz()).build();
excelWriter.write(exportTaskDto.getData(),fieldsDescribeSheet);
excelWriter.finish();
return outputStream.toByteArray();
}
class GoodsFieldsWriteHandler extends AbstractVerticalCellStyleStrategy {
private final WriteCellStyle headWriteCellStyle1;
private final WriteCellStyle headWriteCellStyle2;
private final int headerListSize;
public GoodsFieldsWriteHandler(WriteCellStyle headWriteCellStyle1, WriteCellStyle headWriteCellStyle2, int headerList1Size) {
this.headWriteCellStyle1 = headWriteCellStyle1;
this.headWriteCellStyle2 = headWriteCellStyle2;
this.headerListSize = headerList1Size;
}
@Override
protected WriteCellStyle headCellStyle(CellWriteHandlerContext context) {
Integer columnIndex = context.getColumnIndex();
// 当列数小于必填字段的数量时,使用样式1,否则使用样式2
if (columnIndex < headerListSize) {
return headWriteCellStyle1;
} else {
return headWriteCellStyle2;
}
}
}
- 生成文件效果


1万+

被折叠的 条评论
为什么被折叠?



