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);
  });
}
相关推荐
肖老师xy20 分钟前
Ai生成时间排期进度
javascript·vue.js·elementui
Aliex_git22 分钟前
Vue 错误处理机制源码理解
前端·javascript·vue.js
trayvontang39 分钟前
SpringBoot自动配置原理
spring boot·自动配置·spi·自动配置原理
2501_942818911 小时前
AI 多模态全栈项目实战:Vue3 + Node 打造 TTS+ASR 全家桶!
vue.js·人工智能·node.js
Komorebi゛1 小时前
【Vue3+Element Plus】el-dialog弹窗点击遮罩层无法关闭弹窗问题记录
前端·vue.js·elementui
Java水解2 小时前
springboot: Spring Boot 启动流程详解
spring boot·后端
Craaaayon2 小时前
深入浅出 Spring Event:原理剖析与实战指南
java·spring boot·后端·spring
多仔ヾ2 小时前
Vue.js 前端开发实战之 02-Vue 开发基础(1)
vue.js
不想秃头的程序员3 小时前
前端 Token 无感刷新全解析:Vue3 与 React 实现方案
vue.js·react.js