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);
  });
}
相关推荐
Lisonseekpan17 小时前
Spring Boot 中使用 Caffeine 缓存详解与案例
java·spring boot·后端·spring·缓存
Terio_my17 小时前
Spring Boot Web环境测试配置
spring boot
Damon小智18 小时前
玩转ClaudeCode:通过Excel-MCP实现数据清洗并写入Excel
ai·excel·ai编程·claude·chrome devtools·rpa·claude code
@大迁世界18 小时前
第03章: Vue 3 组合式函数深度指南
前端·javascript·vue.js·前端框架·ecmascript
汤姆yu18 小时前
2025版基于springboot的美食食品商城系统
spring boot·后端·美食
二十雨辰18 小时前
vite与ts的结合
开发语言·前端·vue.js
我是日安18 小时前
从零到一打造 Vue3 响应式系统 Day 25 - Watch:清理 SideEffect
前端·javascript·vue.js
我的div丢了肿么办19 小时前
vue3使用h函数如何封装组件和$attrs和props的区别
前端·javascript·vue.js
kfepiza19 小时前
Spring 如何解决循环依赖 笔记251008
java·spring boot·spring
我的写法有点潮19 小时前
竟然被element-plus背刺了
前端·javascript·vue.js