Java自定义字段导出

实体类

	@ExcelProperty(value = "投资项目名称")
    @ColumnWidth(20)
    private String projectName;

@ExcelProperty :导出的标题名
@ColumnWidth:宽度

@Data
@Slf4j
public class ExportHelper {
    /**
     * 根据export类获取表头信息
     */
    public static List<String> listHeads(Class<?> clazz) {
        Field[] declaredFields = clazz.getDeclaredFields();
        List<String> headList = new ArrayList<>();
        for (Field declaredField : declaredFields) {
            if (declaredField.isAnnotationPresent(ExcelProperty.class)) {
                ExcelProperty annotation = declaredField.getAnnotation(ExcelProperty.class);
                headList.add(annotation.value()[0]);
            }
        }
        return headList;
    }

    /**
     * 根据表头信息获取字段名
     */
    public static List<String> listPropertyName(List<String> heads, Class<?> clazz) {
        Field[] declaredFields = clazz.getDeclaredFields();
        List<String> propertyList = new ArrayList<>();
        for (String head : heads) {
            for (Field declaredField : declaredFields) {
                if (declaredField.isAnnotationPresent(ExcelProperty.class)) {
                    ExcelProperty annotation = declaredField.getAnnotation(ExcelProperty.class);
                    if (head.equals(annotation.value()[0])) {
                        propertyList.add(declaredField.getName());
                    }
                }
            }
        }
        return propertyList;
    }
    }
/**
     * 获取Excel导出头信息
     */
    @GetMapping("/getExportHeads")
    public R<List<String>> getExportHeads() {
        List<String> heads = ExportHelper.listHeads(ExportProject.class);
        return R.ok(heads);
    }

    /**
     * 导出excel
     */
    @PostMapping("exportProject")
    public void exportProject(HttpServletResponse response, @RequestBody SubjectQuery query) throws IOException {
        Assert.notEmpty(query.getHeads(), "自定义导出头不能为空");
        WebHelper.responseDownloadExcel(response, "项目导出");
        List<ExportProject> projects = subjectService.listProjectExport(query);
        List<String> fileList = ExportHelper.listPropertyName(query.getHeads(), ExportProject.class);
        EasyExcel.write(response.getOutputStream(), ExportProject.class).includeColumnFiledNames(fileList).sheet("项目导出").doWrite(projects);
    }


其中getExportHeads这个方法可以给前端返回可以导出的字段,返回结果如图所示

Java自定义字段导出_第1张图片
前端可以选择其中的字段通过query中的字段 heads传递给后端实现自定义导出字段:
Java自定义字段导出_第2张图片

你可能感兴趣的:(excel导出,java,开发语言)