EasyExcel自定义处理器扩展指定行修改样式包括字体颜色
实现
java
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFColor;
import java.util.List;
public class CustomRowWriteHandler implements RowWriteHandler {
private List<Integer> rowIndexToChange;
public CustomRowWriteHandler(List<Integer> rowIndexToChange) {
this.rowIndexToChange = rowIndexToChange;
}
@Override
public void afterRowCreate(WriteSheetHolder writeSheetHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
//获取信息
Sheet sheet = writeSheetHolder.getSheet();
Workbook workbook = sheet.getWorkbook();
//字体颜色
Font font = workbook.createFont();
font.setColor(IndexedColors.BLUE.getIndex());
//设置样式
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(font);
for(Integer rowIndex : rowIndexToChange){
//过滤表头
Row fontRow = sheet.getRow(rowIndex + 1);
if(fontRow != null){
for (Cell cell : fontRow) {
cell.setCellStyle(cellStyle);
}
}
}
}
}
}
// 导出时设置自定义写入处理器
public void exportExcel(List<YourDataClass> data, String fileName, int rowIndexToChange) {
EasyExcel.write(fileName, YourDataClass.class)
.sheet("Sheet1")
.registerWriteHandler(new CustomRowWriteHandler(rowIndexToChange))
.doWrite(data);
}