引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>1.1.2-beta5</version>
</dependency>
写一个样式类实现Easy-Excel写回调
public class ExcelBuilder {
/** EasyExcel Writer */
private ExcelWriter writer;
/** 保存每个sheet的头数据 */
private Map<Integer, List<List<String>>> headMap = new ConcurrentHashMap<>(2);
/** 保存每个Sheet的内容数据 */
private Map<Integer, List<List<Object>>> bodyMap = new ConcurrentHashMap<>(2);
/** Sheet索引 */
private int sheetIndex = 0;
/**
* 创建一个ExcelBuilder对象
*
* @param os 输出流
* @return ExcelBuilder
*/
public ExcelBuilder create(OutputStream os) {
writer =
EasyExcelFactory.getWriterWithTempAndHandler(
null,
os,
ExcelTypeEnum.XLS,
true,
new WriteHandler() {
private Workbook workbook;
private List<List<String>> head;
private List<List<Object>> body;
@Override
public void sheet(int sheetNo, org.apache.poi.ss.usermodel.Sheet sheet) {
}
@Override
public void row(int rowNum, Row row) {
//自定义样式
}
@Override
public void cell(int cellNum, Cell cell) {
//自定义单元格样式
}
});
return this;
}
/**
* 添加sheet的内容
*
* @param sheetName sheet名称
* @param head 头部信息
* @param body 内容信息
* @return ExcelBuilder
*/
public ExcelBuilder addSheet(String sheetName, List<List<String>> head, List<List<Object>> body) {
int sheetNo = ++sheetIndex;
this.headMap.put(sheetNo, head);
this.bodyMap.put(sheetNo, body);
Sheet sheet = new Sheet(sheetNo, 0);
sheet.setSheetName(sheetName);
sheet.setAutoWidth(true);
sheet.setHead(head);
TableStyle tableStyle = new TableStyle();
tableStyle.setTableHeadBackGroundColor(IndexedColors.ROYAL_BLUE);
tableStyle.setTableContentBackGroundColor(IndexedColors.WHITE);
sheet.setTableStyle(tableStyle);
this.writer.write1(body, sheet);
return this;
}
/** 开始构建 */
public void build() {
this.writer.finish();
}
}