import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.AbstractRowHeightStyleStrategy;
import com.alibaba.excel.write.style.row.AbstractRowStyleStrategy;
import org.apache.poi.ss.usermodel.*;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
public class EasyExcelExample {
public static void main(String[] args) {
String fileName = "styled_excel.xlsx";
try (FileOutputStream outputStream = new FileOutputStream(fileName)) {
// 创建ExcelWriterBuilder
ExcelWriterBuilder writerBuilder = EasyExcel.write(outputStream);
// 创建WriteSheet
WriteSheet writeSheet = new ExcelWriterSheetBuilder().build();
// 创建ExcelWriter
ExcelWriter excelWriter = writerBuilder.build();
// 写入数据前,先设置第二行的样式
AbstractRowStyleStrategy rowStyleStrategy = new AbstractRowStyleStrategy() {
@Override
protected void setHeadCellStyle(Cell cell, Head head, Integer relativeRowIndex) {
// 这里不处理表头,直接跳过
}
@Override
protected void setContentCellStyle(Cell cell, WriteSheetHolder writeSheetHolder, Integer relativeRowIndex, Integer relativeColumnIndex) {
if (relativeRowIndex == 1) { // 第二行(索引从0开始)
// 设置字体样式
Font font = workbook.createFont();
font.setFontHeightInPoints((short) 14);
font.setBold(true);
cell.setCellFont(font);
// 设置填充颜色
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(cellStyle);
}
}
};
// 写入数据,应用样式策略
List<List<String>> data = new ArrayList<>();
data.add(List.of("标题1", "标题2", "标题3")); // 表头
data.add(List.of("内容1", "内容2", "内容3")); // 第一行数据
data.add(List.of("内容4", "内容5", "内容6")); // 第二行数据,将应用样式
// ... 可以继续添加更多行数据
// 写入数据到Excel
excelWriter.write(data, writeSheet, rowStyleStrategy);
// 关闭writer,释放内存
excelWriter.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
}