poi导出数据
相当于一次性把excel拿过来,分配树形结构进行操作,若文件大可能会产生内存溢出
因为是树形结构,对于添加删除比较方便
esayexcel
相当于一行一行拿过来进行操作,操作之后再扔出内存
使用,添加依赖
com.alibaba easyexcel2.1.1
编写service层方法
//导出
@Override
public void exportData(HttpServletResponse response) {
try {
//设置文件类型
response.setContentType("application/vnd.ms-excel");
//防止内容中有乱码
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("数据字典", "UTF-8");
//设置响应头
response.setHeader("Content-disposition", "attachment;filename="+ fileName+".xlsx");
//查询数据库得到数据
List dictList = baseMapper.selectList(null);
//因为自己封装了返回类,与实体类字段不匹配
List dictVoList = new ArrayList<>(dictList.size());
for(Dict dict : dictList) {
//dict对象 转成vo对象
DictEeVo dictVo = new DictEeVo();
BeanUtils.copyProperties(dict,dictVo);
dictVoList.add(dictVo);
}
EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictVoList);
} catch (IOException e) {
e.printStackTrace();
}
}
控制层
@ApiOperation(value="导出")
@GetMapping(value = "/exportData")
public void exportData(HttpServletResponse response) {
dictService.exportData(response);
}
vue页面添加按钮
导出 添加方法
methods: { //导出 exportData(){ window.open("http://localhost:8202/admin/cmn/dict/exportData") },导入功能,页面添加按钮
导入 控制层
@ApiOperation(value = "导入") @PostMapping("importData") public R importData(MultipartFile file) { //获取选择之后的文件 dictService.importDictData(file); return R.ok(); }添加监听器
@Component public class DictListener extends AnalysisEventListener{ @Autowired private DictMapper dictMapper; //一行一行读取 @Override public void invoke(DictEeVo dictEeVo, AnalysisContext analysisContext) { //调用方法添加数据库 Dict dict = new Dict(); BeanUtils.copyProperties(dictEeVo,dict); dictMapper.insert(dict); } @Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { } } service层
@Autowired private DictListener dictListener; //导入 @Override public void importDictData(MultipartFile file) { //获取文件内容 将内容加入数据库 try { EasyExcel.read(file.getInputStream(),DictEeVo.class,dictListener).sheet().doRead(); } catch (IOException e) { e.printStackTrace(); } }前端页面
点击上传 只能上传xls文件取消 方法
export default { data() { return { dialogimportVisible:false, //弹框 } }, created() { this.getDictList(1) }, methods: { //导入 importData() { this.dialogimportVisible = true }, onUploadSuccess(response, file) { this.$message.info('上传成功') this.dialogimportVisible = false this.getDictList(1) },



