springboot+vue导出excel并下载

  1. 引入easyexcel依赖
xml 复制代码
<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.3.2</version>
        </dependency>
  1. 编写接口
java 复制代码
/**
     * 批量导出
     *
     * @param ids
     * @return
     */
    @PostMapping("/export")
    public void exportExcel(@RequestBody List<Long> ids, HttpServletResponse response) {
    	// 查询出需要批量导出的数据
        List<Order> orderList = orderService.listByIds(ids);
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            EasyExcel.write(response.getOutputStream(), Order.class)
                    .autoCloseStream(true).build()
                    .write(() -> orderList, new WriteSheet()).finish();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
  1. 前端发起导出请求并下载
javascript 复制代码
const exportExcel = async () => {
  // 发送HTTP GET请求获取Excel文件流
  axios({
    url: url地址,
    method: 'POST',
    responseType: 'blob', // 重要
    data: 批量导出的数据id,
    headers: {
      'Authorization': token // 如果需要token,添加到请求头中
    }
  }).then((response) => {
    // 创建一个Blob对象,内容为后端返回的文件流
    const blob = new Blob([response.data], {type: 'application/vnd.ms-excel'});

    // 创建一个a标签,用于触发下载
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = '订单表.xlsx'; // 下载文件的名称
    link.click();

    // 清理资源
    URL.revokeObjectURL(link.href);
  }).catch((error) => {
    console.error('下载失败:', error);
  });
}
相关推荐
吴声子夜歌21 分钟前
Vue3——渲染函数
前端·vue.js·vue·es6
Ruihong26 分钟前
你的 Vue KeepAlive 组件,VuReact 会编译成什么样的 React 代码?
vue.js·react.js·面试
tycooncool28 分钟前
Spring Boot中集成MyBatis操作数据库详细教程
数据库·spring boot·mybatis
Ruihong32 分钟前
你的 Vue slot 插槽,VuReact 会编译成什么样的 React 代码?
vue.js·react.js·面试
一 乐35 分钟前
房产租赁管理|基于springboot + vue房产租赁管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·房产租赁管理系统
未秃头的程序猿37 分钟前
从零到一:深入浅出分布式锁原理与Spring Boot实战(Redis + ZooKeeper)
spring boot·分布式·后端
2501_913680001 小时前
Vue3项目快速接入AI助手的终极方案 - 让你的应用智能升级
前端·vue.js·人工智能·ai·vue·开源软件
踩着两条虫1 小时前
VTJ:应用场景展示
前端·vue.js·架构
慕容卡卡1 小时前
你所不知道的RAG那些事
java·开发语言·人工智能·spring boot·spring cloud
程序员萌萌2 小时前
基于 Redis 的分布式锁:原理剖析与 Spring Boot 实战(含看门狗续期)
spring boot·redis·分布式锁·看门狗机制