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);
  });
}
相关推荐
从文处安5 小时前
「九九八十一难」组合式函数到底有什么用?
前端·vue.js
用户11489669441056 小时前
VUE3响应式原理——从零解析
vue.js
用户83040713057016 小时前
SPA 首屏加载速度慢怎么解决?
vue.js·webpack
一枚前端小姐姐6 小时前
低代码平台表单设计系统技术分析(实战三)
前端·vue.js·低代码
SuperEugene7 小时前
从 Vue2 到 Vue3:语法差异与迁移时最容易懵的点
前端·vue.js·面试
用户8307196840827 小时前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
Leon7 小时前
新手引导 intro.js 的使用
前端·javascript·vue.js
Forever7_7 小时前
仅用一个技巧,让 JavaScript 性能提速 500%!
前端·vue.js
青屿ovo9 小时前
Vue前端页面版本检测解决方案
前端·vue.js
apollo_qwe12 小时前
深入解析Vue的mixins与hooks:复用逻辑的两种核心方式
vue.js