easyexcel
easyexcel copied to clipboard
如何支持内容单元格背景色交替显示
你好, 目前在我在使用 EasyExcel (版本 3.3.4) 结合 JDK 17 生成 Excel 文件。
有个需求:内容行设置交替的背景颜色,这样每一行都有不同的背景颜色,以两种指定的颜色交替显示。这样可以帮助用户更容易区分每一行,避免看错行。
` // 创建头部的样式策略 WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
WriteFont headFont = new WriteFont();
headFont.setFontHeightInPoints((short) 14);
headWriteCellStyle.setWriteFont(headFont);
// 创建内容的样式策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
WriteFont contentFont = new WriteFont();
contentFont.setFontHeightInPoints((short) 12);
contentWriteCellStyle.setWriteFont(contentFont);
// 样式策略
HorizontalCellStyleStrategy horizontalCellStyleStrategy =
new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);`
上面是我写的样式策略,
我应该怎么改,才能实现「内容行设置交替的背景颜色」的效果。
谢谢。
你好,可以参考 #3806
/** * 获取背景一行白一行灰的表格策略 * * @return */ public static @NotNull HorizontalCellStyleFirstValueStrategy getHorizontalCellStyleStrategy() { WriteCellStyle contentWriteCellStyle1 = getWriteCellStyle(IndexedColors.WHITE); WriteCellStyle contentWriteCellStyle2 = getWriteCellStyle(IndexedColors.GREY_25_PERCENT);
HorizontalCellStyleFirstValueStrategy horizontalCellStyleStrategy = new HorizontalCellStyleFirstValueStrategy();
horizontalCellStyleStrategy.setContentWriteCellStyleList(Arrays.asList(contentWriteCellStyle1, contentWriteCellStyle2));
return horizontalCellStyleStrategy;
}
/**
* 获取表格合并单元格的处理器
* @param white
* @return
*/
private static @NotNull WriteCellStyle getWriteCellStyle(IndexedColors white) {
WriteCellStyle contentWriteCellStyle1 = new WriteCellStyle();
contentWriteCellStyle1.setBorderLeft(BorderStyle.THIN);
contentWriteCellStyle1.setBorderRight(BorderStyle.THIN);
contentWriteCellStyle1.setBorderTop(BorderStyle.THIN);
contentWriteCellStyle1.setBorderBottom(BorderStyle.THIN);
contentWriteCellStyle1.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
// 背景白色
contentWriteCellStyle1.setFillForegroundColor(white.getIndex());
WriteFont contentWriteFont = getWriteFont();
contentWriteCellStyle1.setWriteFont(contentWriteFont);
return contentWriteCellStyle1;
}
/**
* 字体
* @return
*/
private static @NotNull WriteFont getWriteFont() {
WriteFont contentWriteFont = new WriteFont();
contentWriteFont.setFontHeightInPoints((short)16);
contentWriteFont.setColor(IndexedColors.BLACK.getIndex());
return contentWriteFont;
}