核心代码:
后台
public void exportData(HttpServletResponse response) {
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
//这里使用URLEncoder.encode可以防止中文乱码
String fileName = URLEncoder.encode("用户信息", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
List<User> users = baseMapper.selectList(null);
List<UserVo>list=new ArrayList<>();
for(User user:dicts){
UserVo userVo=new UserVo();
BeanUtils.copyProperties(user,userVo);
list.add(userVo);
}
EasyExcel.write(response.getOutputStream(),UserVo.class).sheet("dict")
.doWrite(list);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
前端:
<div class="el-toolbar">
<div class="el-toolbar-body" style="justify-content: flex-start;">
<a href="http://localhost:8088/admin/user/exportData" target="_blank">
<el-button type="text" ><i class="fa fa-plus"/> 导出</el-button>
</a>
</div>
</div>
这里使用a标签并将target赋值为_blank这样可以在一个新的空标签页中进行导出,不影响原来的页面。