easyexcel官方文档https://www.yuque.com/easyexcel/doc/read
一、后端文件导入、导出接口实现
1. 添加依赖
<!--excel解析-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.1</version>
</dependency>
<!--excel解析依赖-->
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
2. 对象
@Data
public class ExcelDictDTO {
@ExcelProperty("id")
private Long id;
@ExcelProperty("上级id")
private Long parentId;
@ExcelProperty("名称")
private String name;
@ExcelProperty("值")
private Integer value;
@ExcelProperty("编码")
private String dictCode;
}
3. ExcelDictDTOListener监听器
@Slf4j
@NoArgsConstructor
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {
private DictMapper dictMapper;
//数据列表
private List<ExcelDictDTO> list = new ArrayList<>();
/**
*每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收
*/
private static final int BATCH_COUNT = 5;
/**
* 把 Mapper层注入到监听器中
* @param dictMapper
*/
public ExcelDictDTOListener(DictMapper dictMapper) {
this.dictMapper = dictMapper;
}
/**
* 这个每一条数据解析都会来调用
* @param data
* @param context
*/
@Override
public void invoke(ExcelDictDTO data, AnalysisContext context) {
log.info("解析到一条记录: {}", data);
//将数据存入数据列表
list.add(data);
// 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
if(list.size() >= BATCH_COUNT){
saveData();
list.clear();
}
}
/**
* 所有数据解析完成了 都会来调用
* @param context
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
//当最后剩余的数据记录数不足BATCH_COUNT时,我们最终一次性存储剩余数据
saveData();
log.info("所有数据解析完成!");
}
/**
* 把数据保存到数据库
*/
private void saveData(){
log.info("{} 条数被存储到数据库......", list.size());
//调用mapper层的批量save方法:save list对象
dictMapper.insertBatch(list);
log.info("{} 条数被存储到数据库成功!", list.size());
}
}
4. COntroller类
/**
* <p>
* 数据字典 前端控制器
* </p>
*
* @author Helen
* @since 2021-02-20
*/
@Api(tags = "数据字典管理")
@RestController
@RequestMapping("/admin/core/dict")
@Slf4j
@CrossOrigin
public class AdminDictController {
@Resource
DictService dictService;
@ApiOperation("Excel数据的批量导入")
@PostMapping("/import")
public R batchImport(
@ApiParam(value = "Excel数据字典文件", required = true)
@RequestParam("file") MultipartFile file){
try {
InputStream inputStream = file.getInputStream();
dictService.importData(inputStream);
return R.ok().message("数据字典数据批量导入成功");
} catch (Exception e) {
throw new BusinessException(ResponseEnum.UPLOAD_ERROR, e);
}
}
@ApiOperation("Excel数据的导出")
@GetMapping("/export")
public void export(HttpServletResponse response) throws IOException {
// 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("mydict", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), ExcelDictDTO.class).sheet("数据字典").doWrite(dictService.listDictData());
}
/*树形数据的两种加载方案
方案一:非延迟加载
需要后端返回的数据结构中包含嵌套数据,并且嵌套数据放在children属性中
方案二:延迟加载
不需要后端返回数据中包含嵌套数据,并且要定义布尔属性hasChildren,表示当前节点是否包含子数据
如果hasChildren为true,就表示当前节点包含子数据
如果hasChildren为false,就表示当前节点不包含子数据
如果当前节点包含子数据,那么点击当前节点的时候,就需要通过load方法加载子数据*/
@ApiOperation("根据上级id获取子节点数据列表")
@GetMapping("/listByParentId/{parentId}")
public R listByParentId(
@ApiParam(value = "上级节点id", required = true)
@PathVariable Long parentId){
List<Dict> dictList = dictService.listByParentId(parentId);
return R.ok().data("list", dictList);
}
}
5. Service类
/**
* <p>
* 数据字典 服务实现类
* </p>
*
* @author Helen
* @since 2021-02-20
*/
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
@Resource
private RedisTemplate redisTemplate;
@Transactional(rollbackFor = {Exception.class})
@Override
public void importData(InputStream inputStream) {
EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDTOListener(baseMapper)).sheet().doRead();
log.info("Excel导入成功");
}
@Override
public List<ExcelDictDTO> listDictData() {
List<Dict> dictList = baseMapper.selectList(null);
//创建ExcelDictDTO列表,将Dict列表转换成ExcelDictDTO列表
ArrayList<ExcelDictDTO> excelDictDTOList = new ArrayList<>(dictList.size());
dictList.forEach(dict -> {
ExcelDictDTO excelDictDTO = new ExcelDictDTO();
BeanUtils.copyProperties(dict, excelDictDTO);
excelDictDTOList.add(excelDictDTO);
});
return excelDictDTOList;
}
@Override
public List<Dict> listByParentId(Long parentId) {
try {
//首先查询redis中是否存在数据列表
List<Dict> dictList = (List<Dict>)redisTemplate.opsForValue().get("srb:core:dictList:" + parentId);
if(dictList != null){
//如果存在则从redis中直接返回数据列表
log.info("从redis中获取数据列表");
return dictList;
}
} catch (Exception e) {
log.error("redis服务器异常:" + ExceptionUtils.getStackTrace(e));
}
//如果不逊在则查询数据库
log.info("从数据库中获取数据列表");
QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
dictQueryWrapper.eq("parent_id", parentId);
//dictQueryWrapper.lambda().eq(Dict::getParentId,parentId);
List<Dict> dictList = baseMapper.selectList(dictQueryWrapper);
//填充hashChildren字段
dictList.forEach(dict -> {
//判断当前节点是否有子节点,找到当前的dict下级有没有子节点
boolean hasChildren = this.hasChildren(dict.getId());
dict.setHasChildren(hasChildren);
});
try {
//将数据存入redis
log.info("将数据存入redis");
redisTemplate.opsForValue().set("srb:core:dictList:" + parentId, dictList, 5, TimeUnit.MINUTES);
} catch (Exception e) {
log.error("redis服务器异常:" + ExceptionUtils.getStackTrace(e));
}
//返回数据列表
return dictList;
}
/**
* 判断当前id所在的节点下是否有子节点
* @param id
* @return
*/
private boolean hasChildren(Long id){
QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
dictQueryWrapper.eq("parent_id", id);
Integer count = baseMapper.selectCount(dictQueryWrapper);
if(count.intValue() > 0){
return true;
}
return false;
}
}
二、前端调用接口
1. dict.js (调用后端接口API)
import request from '@/utils/request'
export default {
listByParentId(parentId) {
//自己封装的axiox
return request({
//后端接口
url: `/admin/core/dict/listByParentId/${parentId}`,
method: 'get'
})
}
}
2. list.vue (导入、导出的主要代码)
<template>
<div class="app-container">
<div style="margin-bottom: 10px;">
<!-- Excel导入按钮 -->
<el-button
@click="dialogVisible = true"
type="primary"
size="mini"
icon="el-icon-download"
>
导入Excel
</el-button>
<!-- Excel导出按钮 -->
<el-button
@click="exportData"
type="primary"
size="mini"
icon="el-icon-upload2"
>
导出Excel
</el-button>
</div>
<!-- dialog -->
<el-dialog title="数据字典导入" :visible.sync="dialogVisible" width="30%">
<el-form>
<el-form-item label="请选择Excel文件">
<el-upload
:auto-upload="true"
:multiple="false"
:limit="1"
:on-exceed="fileUploadExceed"
:on-success="fileUploadSuccess"
:on-error="fileUploadError"
:action="BASE_API + '/admin/core/dict/import'"
name="file"
accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">
取消
</el-button>
</div>
</el-dialog>
<el-table :data="list" border row-key="id" lazy :load="load">
<el-table-column label="名称" align="left" prop="name" />
<el-table-column label="编码" prop="dictCode" />
<el-table-column label="值" align="left" prop="value" />
</el-table>
</div>
</template>
<script>
import dictApi from '@/api/core/dict'
export default {
data() {
return {
dialogVisible: false, //对话框是否显示
BASE_API: process.env.VUE_APP_BASE_API, //获取后端接口地址
list: [] //数据字典列表
}
},
created() {
this.fetchData()
},
methods: {
//获取数据字典列表
fetchData() {
dictApi.listByParentId(1).then(response => {
this.list = response.data.list
})
},
// 上传多于一个文件时
fileUploadExceed() {
this.$message.warning('只能选取一个文件')
},
//上传成功回调:通信成功
fileUploadSuccess(response) {
if (response.code === 0) {
//业务成功
this.$message.success('数据导入成功')
this.dialogVisible = false
} else {
//业务失败
this.$message.error(response.message)
}
},
//上传失败回调:通信失败
fileUploadError(error) {
this.$message.error('数据导入失败')
},
exportData() {
//导出excel并下载
window.location.href = this.BASE_API + '/admin/core/dict/export' //后端接口
},
//加载而集节点
load(tree, treeNode, resolve) {
console.log('tree', tree)
console.log('treeNode', treeNode)
//获取数据
dictApi.listByParentId(tree.id).then(response => {
resolve(response.data.list)
})
}
}
}
</script>