简单的Excel上传和下载(下)
思路:前端一个button按钮,点击,然后触发一个事件,调用后端接口,后端只需要,按照EasyExcel的格式编写
前端
1.按钮
<div class="el-toolbar">
<div class="el-toolbar-body" style="justify-content: flex-start;">
<el-button type="text" @click="exportData"><i class="fa fa-plus"/> 导出</el-button>
</div>
</div>
2.触发事件(exportData)
exportData() {
window.open("http://localhost:8202/admin/cmn/dict/exportData")
},
直接使用window.open()
后端
编写controller层,因为官方直接写在controller层的 ,所以我也直接写在controller层上
请求方式:get
思路:如下
直接照着官方文档操作就可以了
@GetMapping("/download")
public void download(HttpServletResponse response)throws IOException {
//查出所有列表
List<Dict> dictList = dictService.list();
List<DictEeVo> dictEeVoList = new ArrayList<>(dictList.size()); //直接指定大小
//遍历这个表
for (Dict dict : dictList) {
//将所有的值全部给dictEoVo
DictEeVo dictEeVo = new DictEeVo();
//调用beanutils这个功能,将所有的值全部给他
BeanUtils.copyProperties(dict,dictEeVo); //这个要求只需要源对象和目标对象的属性相同,
dictEeVoList.add(dictEeVo);
}
//设置响应头之类的
response.setContentType("application/vnd.ms-excel");
//设置编码类型
response.setCharacterEncoding("utf-8");
//设置
String fileName = URLEncoder.encode("字典文件", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
//写出 路径不能写死哦,改成流的方式,因为如果是别人下载要下载到别人的那里
EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("字典文件").doWrite(dictEeVoList);
}