EasyExcel导出数据到Excel,浏览器提供下载

3 篇文章 1 订阅
1 篇文章 0 订阅

        最近的一个项目需求,需要为用户提供一个导出数据功能,点击批量下载按钮,将所选中的数据导入到Excel文档中供用户下载。如下图

点击批量下载报告后,浏览器提供下载功能

下面提供一下实现该功能的思路

 后端:

对于数据的处理,我使用的是Alibaba提供的EasyExcel组件,十分感谢这些大佬造的轮子,方便了我这种初学者学习与使用!地址链接:写excel · 语雀 (yuque.com)

首先需要导入依赖

<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>easyexcel</artifactId>
			<version>2.2.10</version>
		</dependency>

下面是我的Controller代码

/**
     *  批量下载
     */
    @PostMapping("download")
//    @RequiresPermissions("mt:plan:download")
    public R download(HttpServletResponse response,@RequestBody String[] ids) throws IOException {
        List<PlanEntity> list = planService.selectByIds(ids);
        log.warn("获取数据:\n"+list);
        String fileName=new String("学生表.xlsx".getBytes(), StandardCharsets.UTF_8)+new SimpleDateFormat().format(new Date());
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition","attachment;fileName="+fileName);
        EasyExcel.write(response.getOutputStream(),PlanEntity.class)
                .sheet("test")
                .doWrite(list);
        log.info("导出数据:\n"+list);
        return R.ok().put("fileName",fileName);
    }

EasyExcel.write(response.getOutputStream(),PlanEntity.class)
                .sheet("test")
                .doWrite(list);

其中response.getOutputStream()是表示字节流输出,PlanEntity.class对应的是数据库字段的映射类:Sheet("")是为下载后的工作表取一个名字,doWrite(list)是将获取的列表数据交给组件处理。


对应的实体类需要在每个属性上加上一个注解,@ExcelProperty("xxx"),如图

public class PlanEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	@ExcelProperty("编号")
    private String mtId;

至此,前端调用后端提供的接口就会返回数据回去;我们还需要在前端写一个下载按钮提供下载

前端:

//批量下载
export function downloadExcel (blobPart, filename) {
  const blob = new Blob([blobPart], { type: 'application/vnd.ms-excel' })
  console.log('downloadExcel', blob.size)
  // 创建一个超链接,将文件流赋进去,然后实现这个超链接的单击事件
  const elink = document.createElement('a')
  elink.download = decodeURIComponent(filename)
  elink.style.display = 'none'
  elink.href = URL.createObjectURL(blob)
  document.body.appendChild(elink)
  elink.click()
  URL.revokeObjectURL(elink.href) // 释放URL 对象
  document.body.removeChild(elink)
}

    发送请求时,需要带上responseType: 'blob'

this.$http({
          url: this.$http.adornUrl("/mt/plan/download"),
          method: "post",
          data: this.$http.adornData(ids, false),
          responseType: 'blob'
}
 downloadExcel(data, this.getFileName());

    到这里前后端就写完了,当我们点击批量下载后,我们可以将2下载文件存在我们电脑上的任意一个位置。

如有疑问,欢迎探讨指正!

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值