1.添加依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.6</version>
</dependency>
2.查询需要导出的数据
List<HitEntity> hitEntities = fusionRecordMapper.selectHitEntity(hitNum,rangeNum);
3.处理文件名称乱码
String fileName ="文件名称";
response.reset();
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
//解决不同浏览器压缩包名字含有中文时乱码的问题
String agent = request.getHeader("USER-AGENT");
try {
if (agent.contains("MSIE")||agent.contains("Trident")) {
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
} else {
fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
}
} catch (Exception e) {
e.printStackTrace();
}
response.setHeader("Content-Disposition",
String.format("attachment; filename=\"%s\"",fileName));
try {
//EasyExcel导出表-调用head(获取表头信息方法) dataList(获取表数据信息方法)
EasyExcel.write(response.getOutputStream()).head(head(hitEntities)).
sheet("模板").doWrite(dataList(hitEntities));
} catch (IOException e) {
log.error("写入浏览器异常",e);
}
4.head(获取表头信息方法)
private List<List<String>> head(List<HitEntity> hitEntities) {
List<List<String>> list = new ArrayList<>();
if (ObjectUtil.isEmpty(hitEntities)){
return list;
}
LinkedHashMap<String, String> map = JSON.parseObject(hitEntities.get(0).getUpdateInfo(),
new TypeReference<LinkedHashMap<String, String>>(){} );
Set<String> headSet = map.keySet();
HashSet<String> hashSet2 = new HashSet<>(headSet);
hashSet2.add("是否命中");
for (String headCol:hashSet2){
List<String> headColList = new ArrayList<>();
headColList.add(headCol);
list.add(headColList);
}
return list;
}
5.dataList(获取表数据信息方法)
private List<List<Object>> dataList(List<HitEntity> hitEntities) {
List<List<Object>> list = new ArrayList<>();
if (ObjectUtil.isEmpty(hitEntities)){
return list;
}
for (HitEntity hitEntity:hitEntities){
List<Object> data = new ArrayList<>();
Map<String, String> map = JSON.parseObject(hitEntity.getUpdateInfo(), new TypeReference<Map<String, String>>(){} );
map.put("是否命中",1==hitEntity.getIsHit()?"是":"否");
for (String key: map.keySet()){
data.add(map.get(key));
}
list.add(data);
}
return list;
}
6.实体类
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* @author TG
* @create 2021-04-26 14:32
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("fusion_record")
@ApiModel(value="融合记录 ",description="融合记录 ")
public class HitEntity {
/**
* 更新信息 :更新的字段和值
*/
@ApiModelProperty(value = "更新信息 :更新的字段和值")
private String updateInfo;
@ApiModelProperty(value = "是否命中 :0未命中,1命中")
private Integer isHit;
}