Excel导出
controller层:
@GetMapping("/export")
public ResultJson export(Student student) {
List<Student> list = studentService.list();//将要导出的数据放到list中
ExcelUtil<Student> util = new ExcelUtil<>(Student.class);//利用反射
return util.exportExcel(list, "自动生成数据");调用ExcelUtil里的exportExcel
}
ExcelUtil里的exportExcel:
/**
* 对list数据源将其里面的数据导入到excel表单
*
* @param list 导出数据集合
* @param sheetName 工作表的名称
* @return 结果
*/
public ResultJson exportExcel(List<T> list, String sheetName) {
this.init(list, sheetName, Type.EXPORT); //调用init方法
return exportExcel();
}
ExcelUtil里的init方法:
public void init(List<T> list, String sheetName, Type type) {
if (list == null) {
list = new ArrayList<T>();
}//判断查询出来的学生列表是否为空,若为空则new一个student的ArrayList
this.list = list;
this.sheetName = sheetName;
this.type = type; //赋值给当前类
createExcelField(); //得到所有的定义字段
createWorkbook(); //创建工作簿
}
ExcelUtil里的createExcelField方法:
/**
* 得到所有定义字段
*/
private void createExcelField() {
this.fields = new ArrayList<Object[]>();
List<Field> tempFields = new ArrayList<>();
tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
for (Field field : tempFields) {
// 单注解
if (field.isAnnotationPresent(Excel.class)) {
putToField(field, field.getAnnotation(Excel.class));
}
// 多注解
if (field.isAnnotationPresent(Excels.class)) {
Excels attrs = field.getAnnotation(Excels.class);
Excel[] excels = attrs.value();
for (Excel excel : excels) {
putToField(field, excel);
}
}
}
this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
}
ExcelUtil里的createWorkbook方法:
/**
* 创建一个工作簿
*/
public void createWorkbook() {
this.wb = new SXSSFWorkbook(500);
}
ExcelUtil里的putToField方法:
/**
* 放到字段集合中
*/
private void putToField(Field field, Excel attr) {
if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
this.fields.add(new Object[]{field, attr});
}
}