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);
  });
}
相关推荐
杜子腾dd13 分钟前
8.Excel:数据验证和下拉列表
数据分析·excel
乐享极致38 分钟前
Python 数据可视化进阶:精准插入图表到指定 Excel 工作表
python·信息可视化·excel
拖孩1 小时前
【Nova UI】十四、打造组件库之按钮组件(下):按钮组组件的构建之旅
前端·javascript·vue.js
Rudon滨海渔村1 小时前
[随笔] 升级uniapp旧项目的vue、pinia、vite、dcloudio依赖包等
前端·vue.js·uni-app
weixin_440597451 小时前
Spring Boot 中的条件注解
java·spring boot·后端
Watermelo6172 小时前
Vue3调度器错误解析,完美解决Unhandled error during execution of scheduler flush.
前端·javascript·vue.js·elementui·html·es6·bug
风象南2 小时前
SpringBoot中6种拦截器使用场景
java·spring boot·后端
梦之马3 小时前
spring boot 2升级3 记录
java·spring boot·后端
一城烟雨_8 小时前
vue3 实现将html内容导出为图片、pdf和word
前端·javascript·vue.js·pdf
李少兄10 小时前
解决Spring Boot多模块自动配置失效问题
java·spring boot·后端