CellWriteHandler
is an interface in EasyExcel, a popular Java library for reading and writing Excel files. It is used to customize how data is written to cells during the Excel export process.
Purpose
- It allows developers to modify cell values before they are written.
- It enables custom formatting of data.
- It can be used to apply styles or transformations to cell content dynamically.
How It Works
When EasyExcel writes data to an Excel file, it invokes the CellWriteHandler
at different stages, allowing customization of the cell content.
Implementation Example
Here’s an example of how to use CellWriteHandler
:
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;
public class CustomCellWriteHandler implements CellWriteHandler {
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, int columnIndex, Integer relativeRowIndex, Boolean isHead) {
// Before cell is created (Optional)
}
@Override
public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, int columnIndex, Boolean isHead) {
// After cell is created (Optional)
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, int columnIndex, Boolean isHead) {
// Modify cell styling or values here
if (!isHead) {
CellStyle cellStyle = writeSheetHolder.getSheet().getWorkbook().createCellStyle();
Font font = writeSheetHolder.getSheet().getWorkbook().createFont();
font.setBold(true);
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);
}
}
}
How to Use It
To use the custom handler when writing an Excel file:
EasyExcel.write("output.xlsx", MyData.class)
.registerWriteHandler(new CustomCellWriteHandler()) // Register the custom handler
.sheet("Sheet1")
.doWrite(dataList);
Key Methods
Method | Description |
---|---|
beforeCellCreate() | Called before a cell is created (allows modification of cell properties). |
afterCellCreate() | Called immediately after a cell is created. |
afterCellDispose() | Called after the cell is filled with data, allowing final modifications. |
Use Cases
- Highlighting certain cells (e.g., making headers bold, changing colors).
- Formatting numeric values (e.g., percentages, currency).
- Applying conditional formatting (e.g., highlighting negative values in red).
- Modifying content dynamically (e.g., replacing specific text)