需求: 计划逾期数据进行标红
1. 引入依赖
<dependency>
<groupId>com.alibabagroupId>
<artifactId>easyexcelartifactId>
<version>2.2.7version>
dependency>
2. 创建共用的默认样式
/**
* 默认样式
*
* @return
*/
public static HorizontalCellStyleStrategy defaultStyles() {
//表头样式策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
//设置表头居中对齐
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//表头前景设置淡蓝色
headWriteCellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
WriteFont headWriteFont = new WriteFont();
headWriteFont.setBold(true);
headWriteFont.setFontName("思源黑体");
headWriteFont.setFontHeightInPoints((short) 14);
headWriteCellStyle.setWriteFont(headWriteFont);
//内容样式策略策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 设置背景颜色白色
contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
// 设置垂直居中为居中对齐
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 设置左右对齐为靠左对齐
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 设置单元格上下左右边框为细边框
contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
//创建字体对象
WriteFont contentWriteFont = new WriteFont();
//内容字体大小
contentWriteFont.setFontName("思源黑体");
contentWriteFont.setFontHeightInPoints((short) 12);
contentWriteCellStyle.setWriteFont(contentWriteFont);
// 初始化表格样式
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
return horizontalCellStyleStrategy;
}
3. 创建自定义样式拦截器(指定行样式)
参数值(需要设置标红的行数转为map及需要的颜色index,标题需要的月份参数)
注:明确知道第几行需要设置样式的,可以不设定参数,直接获取cell的行数==指定行进行设置样式
/**
* @Author wendy
* @Date 2020/8/14 5:10 下午
* @Desc 拦截处理单元格创建
*/
public class CellColorSheetWriteHandler implements CellWriteHandler {
/**
* map
* key:第i行
* value:第i行中单元格索引集合
*/
private HashMap<Integer,Integer> map;
/**
* 颜色
*/
private Short colorIndex;
/**
* 月份
*/
private String month;
/**
* 有参构造
*/
public CellColorSheetWriteHandler(HashMap<Integer,Integer> map, Short colorIndex,String month) {
this.map = map;
this.colorIndex = colorIndex;
this.month = month;
}
/**
* 无参构造
*/
public CellColorSheetWriteHandler() {
}
/**
* 在创建单元格之前调用
*/
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
}
/**
* 在单元格创建后调用
*/
@Override
public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
}
/**
* 在单元上的所有操作完成后调用
*/
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
/**
* 根据各自需求进行设置,本示例是整行设置
*/
//当前行的第i列
int i = cell.getColumnIndex();
// 根据单元格获取workbook
Workbook workbook = cell.getSheet().getWorkbook();
if (0 == cell.getRowIndex()) {
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
writeSheetHolder.getSheet().getRow(0).setHeight((short)(3.0*256));
// 获取字体实例
WriteFont headWriteFont = new WriteFont();
//字体样式
headWriteFont.setBold(true);
headWriteFont.setFontHeightInPoints((short) 18);
headWriteFont.setColor(IndexedColors.BLACK.getIndex());
headWriteFont.setFontName("思源黑体");
//单元格样式
headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
headWriteCellStyle.setWriteFont(headWriteFont);
CellStyle cellStyle = StyleUtil.buildContentCellStyle(workbook, headWriteCellStyle);
cell.setCellStyle(cellStyle);
cell.setCellValue("标题" +"("+month+")");
}
//不处理第一行
if (0 != cell.getRowIndex()) {
if (1 == cell.getRowIndex()) {
WriteCellStyle subheadWriteCellStyle = new WriteCellStyle();
// 获取字体实例
WriteFont headWriteFont = new WriteFont();
//字体样式
headWriteFont.setBold(true);
headWriteFont.setFontHeightInPoints((short) 10);
headWriteFont.setColor(colorIndex);
headWriteFont.setFontName("思源黑体");
//单元格样式
subheadWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
subheadWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
subheadWriteCellStyle.setWriteFont(headWriteFont);
CellStyle cellStyle = StyleUtil.buildContentCellStyle(workbook, subheadWriteCellStyle);
cell.setCellStyle(cellStyle);
}
Integer integers = map.get(cell.getRowIndex());
if (integers != null && integers != 1) {
//设置行高
writeSheetHolder.getSheet().getRow(cell.getRowIndex()).setHeight((short) (1.4 * 256));
// 单元格策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 设置背景颜色白色
contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE1.getIndex());
// 设置垂直居中为居中对齐
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 设置左右对齐为中央对齐
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 设置单元格上下左右边框为细边框
contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
// 创建字体实例
WriteFont cellWriteFont = new WriteFont();
// 设置字体大小
cellWriteFont.setFontName("思源黑体");
cellWriteFont.setFontHeightInPoints((short) 14);
//设置字体颜色
cellWriteFont.setColor(colorIndex);
cellWriteFont.setBold(false);
//单元格颜色
//contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
contentWriteCellStyle.setWriteFont(cellWriteFont);
CellStyle cellStyle = StyleUtil.buildHeadCellStyle(workbook, contentWriteCellStyle);
//设置当前行第i列的样式
cell.getRow().getCell(i).setCellStyle(cellStyle);
}
}
}
}
3. 导出方法(测试方法在第5步,可跳过当前)
public void exportExcel(HttpServletResponse response, PlanManagementBasePageDTO pageDTO) {
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("标题", "UTF-8") + ".xlsx");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
//获取逾期数据
List<PlanManagementExportVO> list = export(pageDTO, null);
//装配逾期行数
HashMap<Integer, Integer> map = expiredRowIndex(list);
Date time = new Date(Long.parseLong(pageDTO.getExecuteDate()) * 1000);
SimpleDateFormat format = new SimpleDateFormat("M月");
HorizontalCellStyleStrategy horizontalCellStyleStrategy = defaultStyles();
//设置默认样式
ExcelWriterSheetBuilder writerSheetBuilder = EasyExcel.write(response.getOutputStream(), PlanManagementExportVO.class)
.sheet("计划管理")
.registerWriteHandler(horizontalCellStyleStrategy);
//指定单元格样式
CellColorSheetWriteHandler writeHandler = new CellColorSheetWriteHandler(map, IndexedColors.RED1.getIndex(), format.format(time));
//添加样式
writerSheetBuilder.registerWriteHandler(writeHandler);
//导出
writerSheetBuilder.doWrite(list);
} catch (Exception e) {
e.getStackTrace();
}
}
/**
* 获取逾期计划数据
*/
public List<PlanManagementExportVO> export(PlanManagementBasePageDTO pageDTO, String expiredTag) {
List<PlanManagementExportVO> managementExportVOS = baseMapper.getManagementList(pageDTO, expiredTag);
if (CollectionUtils.isEmpty(managementExportVOS)) {
return new ArrayList<>();
}
AtomicInteger i = new AtomicInteger(2);
managementExportVOS.forEach(item -> {
item.setNum(i.getAndIncrement());
});
return managementExportVOS;
}
/**
* 装配逾期标红map
*/
public HashMap<Integer, Integer> expiredRowIndex(List<PlanManagementExportVO> list) {
HashMap<Integer, Integer> map = new HashMap<>();
map.put(1, 1);
if (CollectionUtils.isEmpty(list)) {
return map;
} else {
list.forEach(data -> {
if (data.getExpiredTag().equals("1")) {
map.put(data.getNum(), data.getNum());
}
});
}
return map;
}
4. 导出实体类
/**
* @Author wendy
* @Date 2021/3/1 15:55
* @Version 1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "计划管理导出展示数据")
//务必设置此属性,否则自定义拦截器设置的样式不起作用
@ContentStyle(horizontalAlignment = HorizontalAlignment.CENTER, verticalAlignment = VerticalAlignment.CENTER)
public class PlanManagementExportVO extends BaseRowModel {
/**
* 行号
*/
@ExcelIgnore
private int num;
/**
* 计划名称
*/
@ApiModelProperty(value = "计划名称")
@ExcelProperty(value = {"标题", "计划名称"}, index = 0)
@ColumnWidth(25)
private String planName;
/**
* 计划类型
*/
@ApiModelProperty(value = "计划类型")
@ExcelProperty(value = {"标题", "计划类型"}, index = 1)
@ColumnWidth(25)
private String planType;
/**
* 责任人员
*/
@ApiModelProperty(value = "责任人员")
@ExcelProperty(value = {"标题", "责任人员"}, index = 2)
@ColumnWidth(35)
private String personLiable;
/**
* 责任部门
*/
@ApiModelProperty(value = "责任部门")
@ExcelProperty(value = {"标题", "责任部门"}, index = 3)
@ColumnWidth(25)
private String liableDept;
/**
* 更新时间
*/
@ApiModelProperty(value = "更新时间")
@ExcelProperty(value = {"标题", "操作时间"}, index = 4)
@ColumnWidth(35)
private Date updatedTime;
@ColumnWidth(15)
@ExcelIgnore
private String expiredTag;
}
5. 测试类
public class Test {
/**
* 导出的数据集合
*/
public static List<PlanManagementExportVO> list;
static {
list = new ArrayList<>();
Collections.addAll(list,
new PlanManagementExportVO(1, "华为P20", "4999.0", "上架", "华为", new Date(), "1"),
new PlanManagementExportVO(2, "华为P30", "5999.0", "上架", "华为", new Date(), "2"),
new PlanManagementExportVO(3, "华为P40", "6999.0", "上架", "华为", new Date(), "0"),
new PlanManagementExportVO(4, "华为P50", "7999.0", "上架", "华为", new Date(), "1"),
new PlanManagementExportVO(5, "华为P60", "8999.0", "上架", "华为", new Date(), "1"),
new PlanManagementExportVO(6, "华为P70", "9999.0", "上架", "华为", new Date(), "1")
);
}
public static void main(String[] args) {
String fileName = null ;
try {
fileName = URLEncoder.encode(new SimpleDateFormat("yyyy-MM-dd-24h").format(new Date()) + ".xlsx", "UTF-8");
}catch (Exception e){
e.getStackTrace();
}
//HorizontalCellStyleStrategy horizontalCellStyleStrategy = defaultStyles();
//设置默认样式
ExcelWriterSheetBuilder writerSheetBuilder = EasyExcel.write(fileName, PlanManagementExportVO.class)
.sheet("计划管理")
.registerWriteHandler(defaultStyles());
//用来记录需要为第`key`行中的第`value.get(i)`列设置样式
HashMap<Integer,Integer > map = new HashMap<>();
map.put(1,1);
map.put(2,2);
map.put(4,4);
//指定单元格样式
CellColorSheetWriteHandler writeHandler = new CellColorSheetWriteHandler(map, IndexedColors.RED1.getIndex());
//添加样式
writerSheetBuilder.registerWriteHandler(writeHandler);
//导出
writerSheetBuilder.doWrite(list);
}
自定义样式拦截器
/**
* @Author wendy
* @Date 2020/8/14 5:10 下午
* @Desc 拦截处理单元格创建
*/
public class CellColorSheetWriteHandler implements CellWriteHandler {
/**
* map
* key:第i行
* value:第i行中单元格索引集合
*/
private HashMap<Integer,Integer> map;
/**
* 颜色
*/
private Short colorIndex;
/**
* 月份
*/
private String month;
/**
* 有参构造
*/
public CellColorSheetWriteHandler(HashMap<Integer,Integer> map, Short colorIndex,String month) {
this.map = map;
this.colorIndex = colorIndex;
this.month = month;
}
/**
* 无参构造
*/
public CellColorSheetWriteHandler() {
}
/**
* 在创建单元格之前调用
*/
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
}
/**
* 在单元格创建后调用
*/
@Override
public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
}
/**
* 在单元上的所有操作完成后调用
*/
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
/**
* 考虑到导出数据量过大的情况,不对每一行的每一个单元格进行样式设置,只设置必要行中的某个单元格的样式
*/
//当前行的第i列
int i = cell.getColumnIndex();
// 根据单元格获取workbook
Workbook workbook = cell.getSheet().getWorkbook();
if (0 == cell.getRowIndex()) {
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
// 获取字体实例
WriteFont headWriteFont = new WriteFont();
//字体样式
headWriteFont.setBold(true);
headWriteFont.setFontHeightInPoints((short) 18);
headWriteFont.setColor(IndexedColors.BLACK.getIndex());
headWriteFont.setFontName("微软雅黑");
//单元格样式
headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
headWriteCellStyle.setWriteFont(headWriteFont);
CellStyle cellStyle = StyleUtil.buildContentCellStyle(workbook, headWriteCellStyle);
cell.setCellStyle(cellStyle);
}
//不处理第一行
if (0 != cell.getRowIndex()) {
Integer integers = map.get(cell.getRowIndex());
if (integers != null && integers != 0) {
if (integers.equals(i)) {
//设置行高
writeSheetHolder.getSheet().getRow(cell.getRowIndex()).setHeight((short) (1.4 * 256));
// 单元格策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 设置背景颜色白色
contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE1.getIndex());
// 设置垂直居中为居中对齐
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 设置左右对齐为中央对齐
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 设置单元格上下左右边框为细边框
contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
// 创建字体实例
WriteFont cellWriteFont = new WriteFont();
// 设置字体大小
cellWriteFont.setFontName("微软雅黑");
cellWriteFont.setFontHeightInPoints((short) 12);
//设置字体颜色
cellWriteFont.setColor(colorIndex);
//单元格颜色
//contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
contentWriteCellStyle.setWriteFont(cellWriteFont);
CellStyle cellStyle = StyleUtil.buildHeadCellStyle(workbook, contentWriteCellStyle);
//设置当前行第i列的样式
cell.getRow().getCell(i).setCellStyle(cellStyle);
}
}
}
}
}