java EasyExcel写一个CellWriteHandler设置标题包含"*"号的部分红色高亮显示
时间: 2024-03-10 11:45:09 浏览: 43
好的,您可以参考以下代码实现:
```java
import com.alibaba.excel.write.handler.CellWriteHandler;
import org.apache.poi.ss.usermodel.*;
public class TitleCellWriteHandler implements CellWriteHandler {
private final String title;
public TitleCellWriteHandler(String title) {
this.title = title;
}
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer integer, Integer integer1, Boolean aBoolean, WriteCellStyle writeCellStyle) {
if (head.getFieldNameList().contains(title)) {
// 获取标题单元格
Cell titleCell = row.getCell(head.getColumnIndex(title));
// 创建富文本样式
Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
Font font = workbook.createFont();
font.setColor(IndexedColors.RED.getIndex());
RichTextString richTextString = new XSSFRichTextString(title);
richTextString.applyFont(title.indexOf("*"), title.length(), font);
// 设置富文本样式
CellStyle cellStyle = titleCell.getCellStyle();
cellStyle.setWrapText(true);
titleCell.setCellStyle(cellStyle);
titleCell.setCellValue(richTextString);
}
}
@Override
public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer integer, Integer integer1, Boolean aBoolean) {
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer integer, Integer integer1, Boolean aBoolean) {
}
}
```
使用示例:
```java
public static void main(String[] args) throws IOException {
try (OutputStream outputStream = new FileOutputStream("test.xlsx");
EasyExcelWriter writer = new EasyExcelWriter(outputStream)) {
// 设置表头
List<String> head = Arrays.asList("标题1", "标题2", "标题3");
// 使用自定义的 CellWriteHandler 设置标题样式
writer.writeHead(head, new TitleCellWriteHandler("标题2*"));
// 写入数据
List<List<Object>> data = Arrays.asList(
Arrays.asList("数据1", "数据2", "数据3"),
Arrays.asList("数据4", "数据5", "数据6"),
Arrays.asList("数据7", "数据8", "数据9")
);
writer.write(data);
}
}
```
这样就可以实现将标题中包含 "*" 的部分使用红色高亮显示了。
阅读全文