行业知识
Java将Map及实体类转化为Excel(支持合并行)
2026-12-04 10:57:43
来源:互联网转载
一、Maven包准备
一、思路
1.函数接收什么? 因为不知道要将什么变为excel,有可能是map,也有可能是某种实体类,所以可以通过List接收,下面是接收的实体类:package com.nuosc.model.vo;import java.lang.reflect.Type;import java.util.*;public class ExcelRequest { private List list; private String primaryKey; private List mergeColumns; private Class clazz; private String title = "Excel表"; public ExcelRequest(List list, String primaryKey, List mergeColumns, String title) { if(!isListHomogeneous(list)){ throw new RuntimeException("列表中类型不唯一"); } this.clazz = list.get(0).getClass(); this.list = list; this.primaryKey = primaryKey; this.mergeColumns = mergeColumns; this.title = title; } public ExcelRequest(List list, String primaryKey, List mergeColumns) { if(!isListHomogeneous(list)){ throw new RuntimeException("列表中类型不唯一"); } this.clazz = list.get(0).getClass(); this.list = list; this.primaryKey = primaryKey; this.mergeColumns = mergeColumns; } public ExcelRequest(List list) { if(!isListHomogeneous(list)){ throw new RuntimeException("列表中类型不唯一"); } this.clazz = list.get(0).getClass(); this.list = list; } public List getList() { return list; } public void setList(List list) { if(!isListHomogeneous(list)){ throw new RuntimeException("列表中类型不唯一"); } this.clazz = list.get(0).getClass(); this.list = list; } public String getPrimaryKey() { return primaryKey; } public void setPrimaryKey(String primaryKey) { this.primaryKey = primaryKey; } public List getMergeColumns() { return mergeColumns; } public void setMergeColumns(List mergeColumns) { this.mergeColumns = mergeColumns; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Class getClazz() { return clazz; } public boolean isListHomogeneous(List list) { if (list.isEmpty()) { throw new RuntimeException("列表为空"); } Type firstType = list.get(0).getClass(); for (int i = 1; i 代码解读: 1.重写构造方法,不可以直接new ExcelReques(),至少要保证里面有list。 2.在构造方法和setList方法中调用isListHomogeneous函数,可以判断list中类型是否一致,并且可以避免list为空的现象。 3.在构造方法和setList方法中拿到list中的class,在后续反射中有用,因为利用FeignClient模块间调用会让Object变为linkedHashMap(上一章内容)。 2.如何知道excel的列名? 对于map而言我们只需要遍历它的key就可以当作列名。 通过自己的需求决定是否遍历List中每一个Map,如果想遍历List中每一个Map,需要一个Set记录已经出现的key,没有出现的key通过add加入到List中,切记不能使用Set存储列名数组,因为Set不能保证顺序,下面是单个遍历key的代码: public List getKeys(Map map){ List list = new ArrayList(); for(Object key : map.keySet()){ if (key instanceof String){ list.add((String) key); } } return list;} 对于实体类而言我们就需要使用反射了。 但是对于实体类我们要求保持一致,不能够存在一个list中存在多个不同的实体类,下面是通过反射拿到属性名的代码: public String getNames(Object obj,List mergeColumns,LinkedHashMap map){ List primaryKeys = new ArrayList(); // 获取列表中第一个元素的Class对象 Class cls = obj.getClass(); // 通过Class对象获取字段列表 Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Name.class)) { // 获取字段上@Name注解的实例 Name nameAnnotation = field.getAnnotation(Name.class); // 将字段名和注解值添加到列表 String value = String.valueOf(nameAnnotation.value()); MergeType type = nameAnnotation.merge(); String key = value != null ? value : field.getName(); map.put(key,field.getName()); if(type.getType() != null){ mergeColumns.add(value); if("primaryKey".equals(nameAnnotation.merge().getType())){ primaryKeys.add(key); } } } } VUtils.throwExceptionIfTrue(primaryKeys.size() > 1,Code.Specification).throwMessage("name为"+primaryKeys+"的字段同时带有Key"); return primaryKeys.get(0);} 代码解读 参数:obj(list中的实体类)、mergeColumns(反射时利用注解记录哪些要合并)、map(key记录字段名或注解值,value记录字段名) VUtils.throwExceptionIfTrue(primaryKeys.size() > 1,Code.Specification).throwMessage("name为"+primaryKeys+"的字段同时带有Key");不必理会可以看做为如果 primaryKeys.size() > 1,抛出错误 下面举个例子: @Datapublic class createContractSummaryExcel { @Name(value = "合同编号",merge = MergeType.Key) private String contractId; @Name("合同名称") private String contractName; @Name(value = "下单时间",merge = MergeType.Column) private String orderTime; @Name("客户名称") private String customerId;} value为别名,带有merge是代表合并,MergeType.Key是代表以该字段为基准进行合并,实体类里面只能有一个,MergeType.Column代表同MergeType.Key一同合并 下面是创建@Name import com.nuosc.model.enums.MergeType;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.PARAMETER,ElementType.FIELD,ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)public @interface Name{ String value(); MergeType merge() default MergeType.Null;}下面是创建MergeTypepublic enum MergeType { Key("primaryKey"), Column("mergeColumn"), Null(null); private final String type; private MergeType(String type) { this.type = type; } public String getType() { return type; }} 3.如何合并列或行? sheet.addMergedRegion(new CellRangeAddress(?,?,?,?)); 通过上面的代码可以控制第几行到第几行合并,第几列到第几列合并 所以我们可以创建一个Map去记录list中带有MergeType.Key的字段是第几行数据变化的 三、代码 Name注解 import com.nuosc.model.enums.MergeType;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.PARAMETER,ElementType.FIELD,ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)public @interface Name{ String value(); MergeType merge() default MergeType.Null;} MergeType枚举类 public enum MergeType { Key("primaryKey"), Column("mergeColumn"), Null(null); private final String type; private MergeType(String type) { this.type = type; } public String getType() { return type; }} ExcelReques实体类 package com.nuosc.model.vo;import java.lang.reflect.Type;import java.util.*;public class ExcelRequest { private List list; private String primaryKey; private List mergeColumns; private Class clazz; private String title = "Excel表"; public ExcelRequest(List list, String primaryKey, List mergeColumns, String title) { if(!isListHomogeneous(list)){ throw new RuntimeException("列表中类型不唯一"); } this.clazz = list.get(0).getClass(); this.list = list; this.primaryKey = primaryKey; this.mergeColumns = mergeColumns; this.title = title; } public ExcelRequest(List list, String primaryKey, List mergeColumns) { if(!isListHomogeneous(list)){ throw new RuntimeException("列表中类型不唯一"); } this.clazz = list.get(0).getClass(); this.list = list; this.primaryKey = primaryKey; this.mergeColumns = mergeColumns; } public ExcelRequest(List list) { if(!isListHomogeneous(list)){ throw new RuntimeException("列表中类型不唯一"); } this.clazz = list.get(0).getClass(); this.list = list; } public List getList() { return list; } public void setList(List list) { if(!isListHomogeneous(list)){ throw new RuntimeException("列表中类型不唯一"); } this.clazz = list.get(0).getClass(); this.list = list; } public String getPrimaryKey() { return primaryKey; } public void setPrimaryKey(String primaryKey) { this.primaryKey = primaryKey; } public List getMergeColumns() { return mergeColumns; } public void setMergeColumns(List mergeColumns) { this.mergeColumns = mergeColumns; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Class getClazz() { return clazz; } public boolean isListHomogeneous(List list) { if (list.isEmpty()) { throw new RuntimeException("列表为空"); } Type firstType = list.get(0).getClass(); for (int i = 1; i FileCreateController类( Excel方法接收ExcelReques) package com.nuosc.file.controller;import com.fasterxml.jackson.databind.ObjectMapper;import com.nuosc.common.exception.VUtils;import com.nuosc.file.service.FileCreateService;import com.nuosc.file.service.Impl.FileCreateServiceImpl;import com.nuosc.model.ov.ControllerRequestMapping;import com.nuosc.model.pojo.Code;import com.nuosc.model.pojo.Result;import com.nuosc.model.vo.ExcelRequest;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import java.util.ArrayList;import java.util.List;import java.util.Map;@ControllerRequestMapping("/file/create")public class FileCreateController { @Autowired ObjectMapper objectMapper; @Autowired FileCreateService fileCreateService; @PostMapping("/excel") public Result Excel(@RequestBody ExcelRequest excelRequest){ FileCreateServiceImpl.Title = excelRequest.getTitle(); List list = excelRequest.getList(); String primaryKey = excelRequest.getPrimaryKey(); List mergeColumns = excelRequest.getMergeColumns(); Class clazz = excelRequest.getClazz(); List newList = new ArrayList(); //判断class是不是Map类型,不是才会反射,如果是的话就不反射 if(!Map.class.isAssignableFrom(clazz)){ try { for (int i = 0; i 1,Code.Specification).throwMessage("name为"+primaryKeys+"的字段同时带有Key"); return primaryKeys.get(0); } public void reflexCreateRow(Object obj,LinkedHashMap names,Row row,String primaryKey,HashMap map,int i,List keys){ Class cls = obj.getClass(); for (int j = 0; j 上面代码中本人最后采用了Oss进行远程存储,如果想只保存本地,可以使用workbook.write() 四、效果展示
上一篇:怎么进北斗授时服务器?
下一篇:存储服务器怎么连接公网?