SpringBoot + Ant Design Vue实现数据导出功能

news2024/9/30 23:30:11

SpringBoot + Ant Design Vue实现数据导出功能

  • 一、需求
  • 二、前端代码实现
    • 2.1 显示实现
    • 2.2 代码逻辑
  • 三、后端代码实现
    • 3.1 实体类
    • 3.2 接收参数和打印模板
    • 3.3 正式的逻辑
    • 3.4 Contorller

一、需求

  • 以xlsx格式导出所选表格中的内容
  • 要求进行分级
  • 设置表头颜色。

二、前端代码实现

2.1 显示实现

首先我们需要添加一个用于到导出的按钮上去,像这样的:

<a-button @click="exportBatchlistVerify">批量导出</a-button>

至于它放哪里,是什么样式可以根据自己的需求决定。

2.2 代码逻辑

按钮有了,下来我们开始实现这个按钮的功能。

  1. 导出数据确定。

表格设置: 表头添加以下代码

<s-table	
	:row-key="(record) => record.id"
	:row-selection="options.rowSelection"
	>

Vue代码 :获取选中的目标ID数组

   import listApi from '@/api/listApi'
	let selectedRowKeys = ref([])
	const options = {
		alert: {
			show: false,
			clear: () => {
				selectedRowKeys = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			},
			//这里是设置复选框的宽度,可以删掉
			columnWidth : 6
		}
	}

按钮功能实现:

	const exportBatchlistVerify = () => {
		if (selectedRowKeys.value.length < 1) {
			message.warning('请输入查询条件或勾选要导出的信息')
		}
		if (selectedRowKeys.value.length > 0) {
			const params = {
				checklistIds: selectedRowKeys.value
					.map((m) => {
						return m
					})
					.join()
			}
			exportBatchChecklist(params)
			return
		}
		exportBatchList(params)

	}
	const exportBatchList= (params) => {
		listApi.listExport(params).then((res) => {
			downloadUtil.resultDownload(res)
			table.value.clearSelected()
		})
	}

listApi: 导入部分和 baseRequest 请参考 Vue封装axios实现

import { baseRequest } from '@/utils/request'
const request = (url, ...arg) => baseRequest(`/list/` + url, ...arg)
	listExport(data) {
		return request('export', data, 'get', {
			responseType: 'blob'
		})
	},

三、后端代码实现

3.1 实体类

我们首先建一个简单的实体,展示将要导出的数据内容:

import com.baomidou.mybatisplus.annotation.TableName;
import com.fhs.core.trans.vo.TransPojo;
import lombok.Data;

/**
 * Auth lhd
 * Date 2023/6/21 9:42
 * Annotate 导出功能测试类
 */
@Data
@TableName("userTest")
public class UserTest implements TransPojo {

    private String id;
    private String name;
    private String tel;
    private String password;
    private String address;
}

3.2 接收参数和打印模板

有了实体类后,我们将开始进行具体的逻辑编写,但在这之前我们需要定义接收前端传参的类,和定义我们的打印模板。

接收参数:

import lombok.Data;

/**
 * Auth lhd
 * Date 2023/6/21 9:46
 * Annotate
 */
@Data
public class UserTestExportParam {
    private String listIds;
}

这部分很简单,我们只需要即将打印的内容ID即可。

打印模板:

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.HeadStyle;
import com.alibaba.excel.enums.poi.FillPatternTypeEnum;
import lombok.Data;

/**
 * Auth lhd
 * Date 2023/6/21 10:10
 * Annotate
 */
@Data
public class UserTestResult {

    @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 40)
    @ExcelProperty({"人物名称"})
    private String name;

    @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 29)
    @ExcelProperty({"基本信息","联系方式 "})
    private String tel;

    @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 31)
    @ExcelProperty({"基本信息","地址 "})
    private String address;

    @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 26)
    @ExcelProperty({"基本信息","不能外露","账号密码 "})
    private String password;

}

打印模板定义了我们们即将打印的表格的表头结构和列名、表头颜色。

备注:通过修改打印模板类的注解,可以实现自定义的表头和表头颜色

3.3 正式的逻辑

映射接口和XML:

  • 接口 UserTestMapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.modular.userTest.entity.UserTest;

/**
 * Auth lhd
 * Date 2023/6/21 10:02
 * Annotate
 */
public interface UserTestMapper extends BaseMapper<UserTest> {
}

  • XML UserTestMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.modular.userTest.mapper.UserTestMapper">

</ma

核心逻辑接口和实现:

  • 逻辑接口 UserTestService
import com.baomidou.mybatisplus.extension.service.IService;
import com.modular.userTest.entity.UserTest;
import com.modular.userTest.param.UserTestExportParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Auth lhd
 * Date 2023/6/21 9:44
 * Annotate
 */
public interface UserTestService extends IService<UserTest> {
    void exportUserTestList(UserTestExportParam listExportParam, HttpServletResponse response) throws IOException;
}

  • 接口实现 UserTestServiceImpl
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.AbstractRowHeightStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fhs.trans.service.impl.TransService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;
import com.modular.userTest.entity.UserTest;
import com.modular.userTest.mapper.UserTestMapper;
import com.modular.userTest.param.UserTestExportParam;
import com.modular.userTest.result.UserTestResult;
import com.modular.userTest.service.UserTestService;
import com.common.excel.CommonExcelCustomMergeStrategy;
import com.common.exception.CommonException;
import com.common.util.CommonDownloadUtil;
import com.common.util.CommonResponseUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Auth lhd
 * Date 2023/6/21 10:01
 * Annotate
 */
@Service
public class UserTestServiceImpl extends ServiceImpl<UserTestMapper, UserTest> implements UserTestService {

    @Resource
    private TransService transService;
    
    @Override
    public void exportUserTestList(UserTestExportParam listExportParam, HttpServletResponse response) throws IOException {
            File tempFile = null;
            try {
                QueryWrapper<UserTest> queryWrapper = new QueryWrapper<>();
                if(ObjectUtil.isNotEmpty(listExportParam.getListIds())) {
                    queryWrapper.lambda().in(UserTest::getId, StrUtil.split(listExportParam.getListIds(), StrUtil.COMMA));
                }
                String fileName = "人物信息表.xlsx";
                List<UserTest> userlists = this.list(queryWrapper);
                if(ObjectUtil.isEmpty(userlists)) {
                    throw new CommonException("无数据可导出");
                }
                transService.transBatch(userlists);
                List<UserTestResult> listResults = userlists.stream()
                        .map(userlist -> {
                            UserTestResult listExportResult = new UserTestResult();
                            BeanUtil.copyProperties(userlist, listExportResult);
                            listExportResult.setName(ObjectUtil.isNotEmpty(listExportResult.getName())?
                                    listExportResult.getName():"无检查地址");
                            return listExportResult;
                        }).collect(Collectors.toList());

                // 创建临时文件
                tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);

                // 头的策略
                WriteCellStyle headWriteCellStyle = new WriteCellStyle();
                WriteFont headWriteFont = new WriteFont();
                headWriteFont.setFontHeightInPoints((short) 14);
                headWriteCellStyle.setWriteFont(headWriteFont);

                // 水平垂直居中
                headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
                headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

                // 内容的策略
                WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
                // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
                contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
                // 内容背景白色
                contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
                WriteFont contentWriteFont = new WriteFont();

                // 内容字体大小
                contentWriteFont.setFontHeightInPoints((short) 12);
                contentWriteCellStyle.setWriteFont(contentWriteFont);

                //设置边框样式,细实线
                contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
                contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
                contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
                contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);

                // 水平垂直居中
                contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
                contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

                // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
                HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle,
                        contentWriteCellStyle);

                // 写excel
                EasyExcel.write(tempFile.getPath(), UserTestResult.class)
                        // 自定义样式
                        .registerWriteHandler(horizontalCellStyleStrategy)
                        // 自动列宽
                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                        // 机构分组合并单元格
                        .registerWriteHandler(new CommonExcelCustomMergeStrategy(listResults.stream().map(UserTestResult::getName)
                                .collect(Collectors.toList()), 0))
                        // 设置第一行字体
                        .registerWriteHandler(new CellWriteHandler() {
                            @Override
                            public void afterCellDispose(CellWriteHandlerContext context) {
                                WriteCellData<?> cellData = context.getFirstCellData();
                                WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
                                Integer rowIndex = context.getRowIndex();
                                if(rowIndex == 0) {
                                    WriteFont headWriteFont = new WriteFont();
                                    headWriteFont.setFontName("宋体");
                                    headWriteFont.setBold(true);
                                    headWriteFont.setFontHeightInPoints((short) 16);
                                    writeCellStyle.setWriteFont(headWriteFont);
                                }
                            }
                        })
                        // 设置表头行高
                        .registerWriteHandler(new AbstractRowHeightStyleStrategy() {
                            @Override
                            protected void setHeadColumnHeight(Row row, int relativeRowIndex) {
                                if(relativeRowIndex == 0) {
                                    // 表头第一行
                                    row.setHeightInPoints(34);
                                } else {
                                    // 表头其他行
                                    row.setHeightInPoints(30);
                                }
                            }
                            @Override
                            protected void setContentColumnHeight(Row row, int relativeRowIndex) {
                                // 内容行
                                row.setHeightInPoints(20);
                            }
                        })
                        .sheet("人物信息表信息")
                        .doWrite(listResults);
                CommonDownloadUtil.download(tempFile, response);
            } catch (Exception e) {
                log.error(">>> 人物信息表导出异常:", e);
                CommonResponseUtil.renderError(response, "导出失败");
            } finally {
                FileUtil.del(tempFile);
            }
        }
}

这里只展示具体逻辑,common开头的公共类和工具类感兴趣的伙伴可以私信我获取~

3.4 Contorller

最后写一个简单的controller类即可:

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.modular.userTest.param.UserTestExportParam;
import com.modular.userTest.service.UserTestService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Auth lhd
 * Date 2023/6/21 10:17
 * Annotate
 */
@RestController
public class UserTestController {

    @Resource
    private UserTestService userTestService;

    @GetMapping(value="/list/export",produces=MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void exportUser(UserTestExportParam listExportParam, HttpServletResponse response) throws IOException {
        userTestService.exportUserTestList(listExportParam, response);
    }
}

我们看看打印效果:
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/670265.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

20230524 taro+vue3+webpack5+pdfjs时打包pdfjs进不来的问题

关闭taro的terser就可以了 terser:{enable:false }

UE中创建异步任务编辑器工具(Editor Utility Tasks)

在UE中我们往往需要执行一些编辑器下的异步任务&#xff0c;例如批量生成AO贴图、批量合并静态模型等&#xff0c;又不想阻碍主线程&#xff0c;因此可以使用Editor Utility Tasks直接创建UE编辑器下的异步任务。 如果你不太了解UE编辑器工具&#xff0c;可以参考这篇文章&…

Spring Boot 中自定义数据校验注解

Spring Boot 中自定义数据校验注解 在 Spring Boot 中&#xff0c;我们可以使用 JSR-303 数据校验规范来校验表单数据的合法性。JSR-303 提供了一些常用的数据校验注解&#xff0c;例如 NotNull、NotBlank、Size 等。但是&#xff0c;在实际开发中&#xff0c;我们可能需要自定…

2023年6月24日(星期六):骑行明郎

2023年6月24日(星期六)&#xff1a;骑行明郎&#xff0c;早8:30到9:00&#xff0c; 大观公园门囗集合&#xff0c;9:30点准时出发 【因迟到者&#xff0c;骑行速度快者&#xff0c;可自行追赶偶遇。】 偶遇地点: 大观公园门囗集合&#xff0c;家住南&#xff0c;东&#xff0c…

(二叉树) 100. 相同的树 ——【Leetcode每日一题】

❓100. 相同的树 难度&#xff1a;简单 给你两棵二叉树的根节点 p 和 q&#xff0c;编写一个函数来检验这两棵树是否相同。 如果两个树在结构上相同&#xff0c;并且节点具有相同的值&#xff0c;则认为它们是相同的。 示例 1&#xff1a; 输入&#xff1a;p [1,2,3], q …

使用代理ip做网页抓取需要注意什么

现在&#xff0c;很多公司为达成目标&#xff0c;都需要抓取大量数据。企业需要根据数据来作出重大决定&#xff0c;因此掌握准确信息至关重要。互联网上有许多宝贵的公共数据。问题是如何轻松采集这些数据&#xff0c;而无需让团队整天手动复制粘贴所需信息?网页抓取的定义越…

Qt学习11:Dialog对话框操作总结

文章目录 QDialogQDialogButtonBoxQMessageBoxQFileDialogQFontDialogQColorDialogQInputDialogQProgressDialog 文章首发于我的个人博客&#xff1a;欢迎大佬们来逛逛 QDialog Qt中使用QDialog来实现对话框&#xff0c;QDialog继承自QWidget&#xff0c;对话框分为**三种**&…

尿的唰唰和笑的哈哈

很多人说看不懂&#xff0c;不知道哪个是真哪个是假。我说都是真的。不同心不同理。全球并不同炎凉。窦唯有句歌词&#xff1a;天堂地狱皆在人间。何勇有句歌词&#xff1a;有人减肥&#xff0c;有人饿死没粮。&#xff08;1&#xff09;产业我过去说过顶天立地。立地&#xff…

专利背后的故事 | 一种异常信息检测方法和装置

Part01 专利发明的初衷 用户和实体行为分析&#xff08;UEBA&#xff09;在2018年入选Gartner为安全团队建议的十大新项目。UEBA近几年一直受到国内安全厂商的热捧。但是对于UEBA的理解&#xff0c;以及具体落实的产品方案&#xff0c;各厂商虽然明显不同&#xff0c;但在对账…

Go应用性能优化的8个最佳实践,快速提升资源利用效率!

作者&#xff5c;Ifedayo Adesiyan 翻译&#xff5c;Seal软件 链接&#xff5c;https://earthly.dev/blog/optimize-golang-for-kubernetes/ 优化服务器负载对于确保运行在 Kubernetes 上的 Golang 应用程序的高性能和可扩展性至关重要。随着企业越来越多地采用容器化的方式和 …

HOOPS Native Platform 2023 cRACK

将高级 3D 工作流程添加到桌面和移动应用程序 HOOPS 原生平台集成了三种用于桌面和移动应用程序开发的先进 HOOPS 技术&#xff0c;包括高性能图形 SDK、CAD 数据访问工具包和 3D 数据发布 API。 ​ ​ 构建 3D 原生应用 借助桌面和移动设备上的 HOOPS 原生平台&#xff0c;快…

一个初级程序员该在哪接项目练手?

作为一个初级程序员&#xff0c;想要通过兼职接单赚钱&#xff0c;离不开项目练手。但不得不说&#xff0c;初级程序员想要通过接私活获取收入还是相对比较困难的&#xff0c;如果对接私活比较感兴趣的朋友&#xff0c;可以参考这条路径&#xff1a; 在GitHub上学习大佬的项目…

【WebLogic】WebLogic 10.3.6.0部署应用包后报错

问题背景&#xff1a; WebLogic 10.3.6.0部署应用包后出现报错【posted content exceeds max post size】&#xff0c;此报错会导致应用部署的目标服务实例无法成功启动。 报错信息截图如下所示&#xff1a; 根据报错信息&#xff0c;查询相关MOS文档&#xff0c;发现问题原因是…

网络能成为AI加速器吗

网络能成为AI加速器吗 摘要 人工神经网络&#xff08;NNs&#xff09;在许多服务和应用中扮演越来越重要的角色&#xff0c;并对计算基础设施的工作负载做出了重要贡献。在用于延迟敏感的服务时&#xff0c;NNs通常由CPU处理&#xff0c;因为使用外部专用硬件加速器会效率低下…

Magisk hide/Denylist 核心原理分析 ROOT隐藏的实现浅论

前言 当手机安装magisk后&#xff0c;全局的挂载空间会受到变更&#xff0c;magisk给我们挂载上了一个su二进制&#xff0c;这就是我们能够访问到su命令的原因 无论是Magisk hide还是Denylist&#xff0c;我们都可以将它们的工作分成两个部分&#xff0c;第一个部分是如何监控…

vue2中引入天地图及相关配置

前言 项目中需要引入特殊用途的地图&#xff0c;发现天地图比高德地图、百度地图要更符合需求&#xff0c;于是看了看天地图。 正文 vue2项目中如何引入天地图并对相关的配置进行修改使用呢&#xff1f;官方给的4.0版本的使用说明。 引入&#xff1a; 进入到public/index.html中…

使用逻辑回归LogisticRegression来对我们自己的数据excel或者csv数据进行分类--------python程序代码,可直接运行

文章目录 一、逻辑回归LogisticRegression是什么&#xff1f;二、逻辑回归LogisticRegression进行分类的具体步骤二、逻辑回归LogisticRegression进行二分类的详细代码三、逻辑回归LogisticRegression的广泛用途总结 一、逻辑回归LogisticRegression是什么&#xff1f; 逻辑回…

小白白也能学会的 PyQt 教程 —— QRadioButton 介绍以及基本使用

文章目录 一、QRadioButton快速入门1. QRadioButton简介2. QRadioButton快速上手 二、响应单选按钮点击事件1、信号和槽机制&#xff1a;2、创建槽函数来响应单选按钮点击&#xff1a;3、示例&#xff1a;执行特定操作或显示相关内容&#xff1a; 三、单选按钮的常用功能和属性…

三维形体投影面积

&#x1f388; 算法并不一定都是很难的题目&#xff0c;也有很多只是一些代码技巧&#xff0c;多进行一些算法题目的练习&#xff0c;可以帮助我们开阔解题思路&#xff0c;提升我们的逻辑思维能力&#xff0c;也可以将一些算法思维结合到业务代码的编写思考中。简而言之&#…

petalinux 生成SDK报错排除

AAA: 在项目文件下新建Qt5文件夹文件夹内新建文件并且设置对应参数 文件夹路径&#xff1a; project-spec/meta-user/recipes-qt/qt5 新建文件 vim ./qt5/qt3d_%.bbappend vim ./qt5/qtquickcontrols2_%.bbappend vim ./qt5/qtserialbus_%.bbappend 文件内容 qt3d_%.bbap…