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);
  });
}
相关推荐
程序员张32 小时前
SpringBoot计时一次请求耗时
java·spring boot·后端
速易达网络6 小时前
RuoYi、Vue CLI 和 uni-app 结合构建跨端全家桶方案
javascript·vue.js·低代码
lyj1689977 小时前
vue-i18n+vscode+vue 多语言使用
前端·vue.js·vscode
麦兜*8 小时前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
KK溜了溜了9 小时前
JAVA-springboot 整合Redis
java·spring boot·redis
大只鹅9 小时前
解决 Spring Boot 对 Elasticsearch 字段没有小驼峰映射的问题
spring boot·后端·elasticsearch
天河归来9 小时前
使用idea创建springboot单体项目
java·spring boot·intellij-idea
IT_10249 小时前
Spring Boot项目开发实战销售管理系统——数据库设计!
java·开发语言·数据库·spring boot·后端·oracle
武昌库里写JAVA10 小时前
Oracle如何使用序列 Oracle序列使用教程
java·开发语言·spring boot·学习·课程设计
爱代码的小黄人10 小时前
Excel VLOOKUP函数使用详解:原理、格式、常见错误与解决方案
excel