使用easyexcel导出数据

该代码示例展示了如何在Java后端使用EasyExcel库生成Excel文件并设置响应头以实现导出用户信息的功能。前端通过A标签触发导出,新标签页打开以避免影响原页面。处理过程中用到了BeanUtils复制对象属性以及URL编码防止中文乱码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

核心代码:

后台

    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这样可以在一个新的空标签页中进行导出,不影响原来的页面。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值