pom文件导入jar包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.4</version>
</dependency>
生成excel的实体类:
@Data
public class TaxationModel {
private List<XX1> xx1;
private List<XX2> xx2;
private List<XX3> xx3;
private List<XX4> xx4;
private List<XX5> xx5;
private List<XX6> xx6;
}
@Data
@EqualsAndHashCode
@ContentRowHeight(60)//内容单元格的高度
@ColumnWidth(25)//所有单元格的宽
@HeadRowHeight(20)//标题单元格的高度
public class XX1 {
@ExcelProperty("xx")
private String xx;
@ExcelProperty("xx")
private String xx;
@ExcelProperty("xx")
private String xx;
@ExcelProperty("xx")
private String xx;
}
封装工具类:
/**
* 根据入参创建excel 多个sheet
* @param excelTestModel
* @return
*/
public static byte[] createSheetsExcel(ExcelModel<?> excelTestModel) {
Class<?> clazz = excelTestModel.getClazz();
Object data = excelTestModel.getData();
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
// 头的策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
// 背景色
headWriteCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short) 12);
headWriteFont.setFontName("等线");
headWriteCellStyle.setWriteFont(headWriteFont);
// 内容的策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//设置 自动换行
contentWriteCellStyle.setWrapped(true);
//设置 垂直居中
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
WriteFont contentWriteFont = new WriteFont();
contentWriteFont.setFontName("等线");
contentWriteCellStyle.setWriteFont(contentWriteFont);
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
ExcelWriter excelWriter = EasyExcel.write(arrayOutputStream, clazz).build();
Field[] fields = data.getClass().getDeclaredFields();
int sheetNum = 1;//sheet个数
for (Field field : fields) {
Type fieldType = field.getGenericType();
String fieldName = field.getName();//属性名
field.setAccessible(true);
//获取所有数据 list
List<?> propertyList = null;
try {
propertyList = (List<?>) field.get(data);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
if (fieldType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) fieldType;
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
//获取list的泛型类型
for (Type type : actualTypeArguments) {
if (type instanceof Class) {
Class<?> genericClass = (Class<?>) type;
WriteSheet writeSheet = EasyExcel.writerSheet(sheetNum++, SheetNameEnum.getNameByCode(fieldName))
.registerWriteHandler(horizontalCellStyleStrategy)
.head(genericClass)
.build();
excelWriter.write(propertyList, writeSheet);
}
}
}
}
excelWriter.finish();
return arrayOutputStream.toByteArray();
}