Easy-Excel+vue3选中表格内容批量导出

目录

一、前端代码

二、后端代码

[2.1 pom.xml](#2.1 pom.xml)

[2.2 MyBatisPlusConfig](#2.2 MyBatisPlusConfig)

[2.3 SwaggerConfig](#2.3 SwaggerConfig)

[2.4 ProductController](#2.4 ProductController)

[2.5 ProductService](#2.5 ProductService)

[2.6 ProductDao](#2.6 ProductDao)

[2.7 Product](#2.7 Product)

三、效果

四、源码和数据库


一、前端代码

前端页面

javascript 复制代码
<template>
  <el-button type="success" @click="exportSelectedRows">导出选中行</el-button>

  <el-table
    :data="tableData"
    border
    style="width: 100%"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" align="center" />
    
    <!-- 编号列 -->
    <el-table-column label="id" align="center">
      <template #default="scope">{{ scope.row.id }}</template>
    </el-table-column>

    <!-- 商品名称列 -->
    <el-table-column prop="name" label="商品名称" align="center" min-width="120" />

    <!-- 商品价格列 -->
    <el-table-column prop="price" label="商品价格" align="center" min-width="120" />

    <!-- 商品简介列 -->
    <el-table-column prop="brief" label="商品简介" align="center" min-width="250">
      <template #default="{ row }">
        <div v-html="row.brief"></div>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { productApi } from '@/api/index';

const tableData = ref([]);
const selectedRows = ref([]); // 存储选中的行
const router = useRouter();

// 查询商品信息
const getProductList = async () => {
  try {
    const res = await productApi.select.call();
    if (res && res.status === 200) {
      tableData.value = res.data;
    } else {
      ElMessage.error('获取数据失败');
    }
  } catch (error) {
    ElMessage.error('请求失败: ' + (error as Error).message);
  }
};

// 当表格的选择发生变化时调用此函数
const handleSelectionChange = (rows:any) => {
  selectedRows.value = rows;
};

// 导出选中的行
const exportSelectedRows = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择至少一行数据!');
    return;
  }

  // 获取选中行的 ID
  const ids = selectedRows.value.map(row => row.id);

  // 构造下载 URL
  const downloadUrl = `/api/product/exportSelected?ids=${ids.join(',')}`;

  // 创建一个隐藏的可下载链接
  const linkElement = document.createElement('a');
  linkElement.setAttribute('href', downloadUrl);
  linkElement.setAttribute('download', 'selectedExport.xlsx'); // 指定文件名
  document.body.appendChild(linkElement); // 必须将链接元素添加到文档中
  linkElement.click(); // 触发点击
  linkElement.remove(); // 下载完成后移除元素
};

onMounted(() => {
  getProductList();
});
</script>

<style scoped>
/* 可选:增加一些自定义样式 */
.el-table th {
  text-align: center !important;
}
</style>

二、后端代码

2.1 pom.xml

XML 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.12.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.by</groupId>
    <artifactId>springboot_excel</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_excel</name>
    <description>springboot_excel</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <!--下面坐标根据自己使用的SpringBoot版本二选一-->
            <!--SpringBoot2使用此版本-->
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.0.32</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>2.3.3</version>
        </dependency>
<!--        easy excel 依赖-->
        <!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.1.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>3.1.3</version>
        </dependency>



    </dependencies>

    <build>
        <!-- 项目打包时会将java目录中的*.xml文件也进行打包 -->



        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2.2 MyBatisPlusConfig

java 复制代码
/*
 * Copyright (c) 2020, 2024, webrx.cn All rights reserved.
 *
 */
package com.by.config;

import com.baomidou.mybatisplus.annotations.DataSource;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
 * <p>Project: springboot_excel - MyBatisPlusConfig</p>
 * <p>Powered by webrx On 2024-08-05 15:14:25</p>
 * <p>描述:<p>
 *
 * @author 简单遗忘 [814736551@qq.com]
 * @version 1.0
 * @since 17
 */
public class MyBatisPlusConfig {
    @Primary
    @Bean("db1SqlSessionFactory")
    public SqlSessionFactory db1SqlSessionFactory(DataSource dataSource) throws Exception {
        /**
         * 使用 mybatis plus 配置
         */
        MybatisSqlSessionFactoryBean b1 = new MybatisSqlSessionFactoryBean();
        System.out.println("dataSourceLyz"+dataSource.toString());
        b1.setDataSource((javax.sql.DataSource) dataSource);
        b1.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        return b1.getObject();
    }
}

2.3 SwaggerConfig

java 复制代码
package com.by.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket docket(Environment environment){

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(true)//关闭swagger,默认是true
                .select()
                //RequestHandlerSelectors:配置要扫描的方式,有basePackage("路径")、any():扫描全部,none():全部不扫描
                //RequestHandlerSelectors.withMethodAnnotation():扫描方法上的注解
                //.withClassAnnotation():扫描类上的注解
                .apis(RequestHandlerSelectors.basePackage("com.beiyou"))//指定扫描的包
                .paths(PathSelectors.ant("/**"))//设置请求路径,这里是带有hello的请求路径
                .build() ;
    }

    private ApiInfo apiInfo(){
        //  Contact contact = new Contact("黑米", "https://blog.csdn.net", "xxx@qq.com");
        return new ApiInfo(
                "商品组的Api",
                "请老大检阅",
                "v2.0",
                "https://www.baidu.com",
                null,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList()
        );
    }

}

2.4 ProductController

java 复制代码
/*
 * Copyright (c) 2020, 2024, webrx.cn All rights reserved.
 *
 */
package com.by.controller;


import com.alibaba.excel.EasyExcel;
import com.by.model.Product;
import com.by.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 黄远超
 */
@RestController
@RequestMapping("/api/product")
public class ProductController {
    @Autowired
    private ProductService productService;
    /**
     * 查询商品
     */
    @GetMapping
    public List<Product> select() {
        return productService.getAllProducts();
    }

   @GetMapping("/exportSelected")
    public void exportSelected(@RequestParam(value = "ids") String ids,
                               HttpServletResponse response) throws IOException {
        try {
            // 将逗号分隔的字符串转换为 Long 数组
            List<Long> idList = Arrays.stream(ids.split(","))
                    .map(Long::valueOf)
                    .collect(Collectors.toList());

            // 设置文件名
            String fileName = "selectedExport" + System.currentTimeMillis() + ".xlsx";

            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 获取选中行的数据
            List<Product> products = productService.selectByIds(idList);

            // 开始导出数据
            EasyExcel.write(response.getOutputStream(), Product.class)
                    .sheet("选中行")
                    .doWrite(products);

            // 关闭输出流
            response.getOutputStream().close();
        } catch (Exception e) {
            // 处理异常
            e.printStackTrace();
        }
    }

}

2.5 ProductService

java 复制代码
/*
 * Copyright (c) 2020, 2024, webrx.cn All rights reserved.
 *
 */
package com.by.service;

import com.alibaba.excel.EasyExcel;

import com.by.dao.ProductDao;
import com.by.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 黄远超
 */
@Service
public class ProductService {
    @Autowired
    private ProductDao productDao;
//    mybatis -plus 查询

    /**
     * 导出数据到 Excel 文件
     */
    public void exportData(List<Product> productList, String fileName) {
        // 创建一个写入器
        EasyExcel.write(fileName, Product.class)
                .sheet("Sheet1") // 设置表单名
                .doWrite(productList); // 写入数据
    }

    public List<Product> getAllProducts() {
        return productDao.selectList(null);
    }

    public List<Product> selectByIds(List<Long> ids) {
        return productDao.selectBatchIds(ids);
    }
}

2.6 ProductDao

java 复制代码
package com.by.dao;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.by.model.Product;
import org.apache.ibatis.annotations.Mapper;

/**
 * @author 黄远超
 */
@Mapper
public interface ProductDao extends BaseMapper<Product> {
}

2.7 Product

java 复制代码
/*
 * Copyright (c) 2020, 2024, webrx.cn All rights reserved.
 *
 */
package com.by.model;

import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>Project: springboot_excel - Product</p>
 * <p>Powered by webrx On 2024-08-02 23:30:21</p>
 * <p>描述:<p>
 *
 * @author 简单遗忘 [814736551@qq.com]
 * @version 1.0
 * @since 17
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@TableName("205_product")
public class Product {
    @TableId(value = "id", type = IdType.AUTO)
    @ExcelProperty("编号")
    private Integer id ;
    @ExcelProperty("商品名称")
    private String name;
    @ExcelProperty("商品价格")
    private BigDecimal price;
    @ExcelProperty("商品简介")
    private String brief;
}

三、效果

四、源码和数据库

记得不要白嫖,点一下star

https://gitee.com/huang-yuanchao1111/vue3--spring-boot.git

相关推荐
前端小小王28 分钟前
React Hooks
前端·javascript·react.js
迷途小码农零零发38 分钟前
react中使用ResizeObserver来观察元素的size变化
前端·javascript·react.js
娃哈哈哈哈呀1 小时前
vue中的css深度选择器v-deep 配合!important
前端·css·vue.js
菠萝蚊鸭1 小时前
Dhatim FastExcel 读写 Excel 文件
java·excel·fastexcel
一只小灿灿1 小时前
VB.NET在 Excel 二次开发中的全面应用
.net·excel
旭东怪1 小时前
EasyPoi 使用$fe:模板语法生成Word动态行
java·前端·word
ekskef_sef3 小时前
32岁前端干了8年,是继续做前端开发,还是转其它工作
前端
sunshine6413 小时前
【CSS】实现tag选中对钩样式
前端·css·css3
真滴book理喻4 小时前
Vue(四)
前端·javascript·vue.js
蜜獾云4 小时前
npm淘宝镜像
前端·npm·node.js