使用VUE+SpringBoot+EasyExcel 整合导入导出数据
使用VUE+SpringBoot+EasyExcel 整合导入导出数据
创建一个普通的maven项目即可
项目目录结构

1 前端
存放在resources/static 下
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<!-- 引入样式 -->
<link
rel="stylesheet"
href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"
/>
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<div class="app-container">
<div style="margin-bottom: 10px">
<el-button
@click="dialogVisible = true"
type="primary"
size="mini"
icon="el-icon-download"
>
导入Excel
</el-button>
<el-dialog
title="数据字典导入"
:visible.sync="dialogVisible"
width="30%"
>
<el-form>
<el-form-item label="请选择Excel文件">
<el-upload
:auto-upload="true"
:multiple="false"
:limit="1"
:on-exceed="fileUploadExceed"
:on-success="fileUploadSuccess"
:on-error="fileUploadError"
:action="importUrl"
name="file"
accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
>
<!--accept 只接受某种格式的文件-->
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
</div>
</el-dialog>
<!-- 导出 -->
<el-button
@click="exportData"
type="primary"
size="mini"
icon="el-icon-upload2"
>
导出Excel
</el-button>
<!-- 数据展示 -->
<el-table :data="list" stripe style="width: 100%">
<el-table-column prop="name" label="姓名" width="180">
</el-table-column>
<el-table-column prop="birthday" label="生日" width="180">
</el-table-column>
<el-table-column prop="salary" label="薪资"> </el-table-column>
</el-table>
<div>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="pageNum"
:page-sizes="[2, 5, 10, 20]"
:page-size="pageSize"
background
layout="total, sizes, prev, pager, next, jumper"
:total="total"
>
</el-pagination>
</div>
</div>
</div>
</div>
</body>
<script>
new Vue({
el: '#app',
data() {
return {
dialogVisible: false, //文件上传对话框是否显示
list: [], // 字典的数据
importUrl: 'http://localhost:8811/api/excel/import',
pageNum: 1, // 页数
pageSize: 5, // 每页条数
total: 1000,
}
},
created() {
this.showList()
},
methods: {
showList() {
//使用自定义配置
const request = axios.create({
baseURL: 'http://localhost:8811', //url前缀
timeout: 1000, //超时时间
// headers: { token: 'helen123456' }, //携带令牌
})
request
.get('/api/excel/list', {
params: {
pageNum: this.pageNum,
pageSize: this.pageSize,
},
})
.then((res) => {
this.total = res.data.size
this.list = res.data.list
console.log(res)
})
},
// 上传多于一个文件时
fileUploadExceed() {
this.$message.warning('只能选取一个文件')
},
// 导出
exportData() {
window.location.href = 'http://localhost:8811/api/excel/export'
},
//上传成功回调
fileUploadSuccess(response) {
if (response.code === 0) {
this.$message.success('数据导入成功')
this.dialogVisible = false
} else {
this.$message.error(response.message)
}
},
//上传失败回调
fileUploadError(error) {
this.$message.error('数据导入失败')
},
/**
* 用户所选择当前页面展示的数据条数
*/
handleSizeChange(val) {
console.log(`每页 ${val} 条`)
this.pageSize = val
this.showList()
},
handleCurrentChange(val) {
console.log(`当前页: ${val}`)
this.pageNum = val
this.showList()
},
},
})
</script>
</html>
2 数据库
CREATE TABLE `student` (
`name` varchar(255) DEFAULT NULL COMMENT '姓名',
`birthday` datetime DEFAULT NULL COMMENT '生日',
`salary` decimal(10,4) DEFAULT NULL COMMENT '薪资'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
3 后端
3.1 contrller
StudentController
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/api/excel/")
public class StudentController {
@Resource
private StudentMapper studentMapper;
@GetMapping("list")
public HashMap<String, Object> list(@RequestParam int pageNum,@RequestParam int pageSize){
// 分页查询
Page<Student> page = new Page<>(pageNum, pageSize);
studentMapper.selectPage(page,null);
// 封装数据
HashMap<String, Object> map = new HashMap<>();
ArrayList<ExcelStudentDTO> excelDictDTOList = new ArrayList<>();
// 转换数据
page.getRecords().forEach(student -> {
ExcelStudentDTO studentDTO = new ExcelStudentDTO();
BeanUtils.copyProperties(student,studentDTO);
excelDictDTOList.add(studentDTO);
});
map.put("list",excelDictDTOList);
map.put("size",page.getTotal());
return map;
}
/**
* 导入
* @param file 文件对象
*/
@RequestMapping("import")
@Transactional(rollbackFor = {Exception.class})
public String importData( @RequestParam("file") MultipartFile file){
try {
// 读取文件流
EasyExcel.read
(file.getInputStream(),// 前端上传的文件
ExcelStudentDTO.class,// 跟excel对应的实体类
new ExcelDictDTOListener(studentMapper))// 监听器
.excelType(ExcelTypeEnum.XLSX)// excel的类型
.sheet("模板").doRead();
log.info("importData finished");
} catch (IOException e) {
log.info("失败");
e.printStackTrace();
}
return "上传成功";
}
/**
* 导入
*/
@GetMapping("export")
public String exportData(HttpServletResponse response){
try {
// 设置响应体内容
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("myStu", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream()
,ExcelStudentDTO.class).sheet().doWrite(studentMapper.selectList(null));
} catch (Exception e) {
e.printStackTrace();
}
return "上传成功";
}
}
3.2 mapper
StudentMapper
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
void insertBatch(List<ExcelStudentDTO> list);
}
StudentMapper.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="look.word.mapper.StudentMapper">
<insert id="insertBatch" >
insert into student(name, birthday, salary)
values
<foreach collection="list" item="item" separator=",">
(
#{item.name} ,
#{item.birthday} ,
#{item.salary}
)
</foreach>
</insert>
</mapper>
3.3 bean
ExcelStudentDTO
导入数据时 要保证excel中列名和ExcelStudentDTO一致奥
/**
* excel对应的实体类
* @author jiejie
*/
@Data
public class ExcelStudentDTO {
// excel中的列名
@ExcelProperty("姓名")
private String name;
@ExcelProperty("生日")
private Date birthday;
@ExcelProperty("薪资")
private BigDecimal salary;
}
Student
/**
* 数据库对应的实体类
* @author jiejie
*/
@Data
@TableName(value = "student")
public class Student {
/**
* 姓名
*/
@TableField(value = "name")
private String name;
/**
* 生日
*/
@TableField(value = "birthday")
private Date birthday;
/**
* 薪资
*/
@TableField(value = "salary")
private BigDecimal salary;
public static final String COL_NAME = "name";
public static final String COL_BIRTHDAY = "birthday";
public static final String COL_SALARY = "salary";
}
3.3 listener
EasyExcel读取文件需要用到
ExcelDictDTOListener
/**
* 监听
* 再读取数据的同时 对数据进行插入操作
* @author : look-word
* @date : 2022-05-10 21:35
**/
@Slf4j
//@AllArgsConstructor //全参
@NoArgsConstructor //无参
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelStudentDTO> {
/**
* 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收
*/
private static final int BATCH_COUNT = 5;
List<ExcelStudentDTO> list = new ArrayList<ExcelStudentDTO>();
private StudentMapper studentMapper;
//传入mapper对象
public ExcelDictDTOListener(StudentMapper studentMapper) {
this.studentMapper = studentMapper;
}
/**
*遍历每一行的记录
* @param data
* @param context
*/
@Override
public void invoke(ExcelStudentDTO data, AnalysisContext context) {
log.info("解析到一条记录: {}", data);
list.add(data);
// 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
if (list.size() >= BATCH_COUNT) {
saveData();
// 存储完成清理 list
list.clear();
}
}
/**
* 所有数据解析完成了 都会来调用
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// 这里也要保存数据,确保最后遗留的数据也存储到数据库
saveData();
log.info("所有数据解析完成!");
}
/**
* 加上存储数据库
*/
private void saveData() {
log.info("{}条数据,开始存储数据库!", list.size());
studentMapper.insertBatch(list); //批量插入
log.info("存储数据库成功!");
}
}
3.5 config
mybatisPlus分页插件
MybatisPlusConfig
@Configuration
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,
* 需要设置 MybatisConfiguration#useDeprecatedExecutor = false
* 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
paginationInnerInterceptor.setDbType(DbType.MYSQL);
paginationInnerInterceptor.setOverflow(true);
interceptor.addInnerInterceptor(paginationInnerInterceptor);
return interceptor;
}
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> configuration.setUseDeprecatedExecutor(false);
}
}
3.6 配置文件
application.yaml
server:
port: 8811
spring:
datasource: # mysql数据库连接
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/2022_source_springboot?serverTimezone=GMT%2B8&characterEncoding=utf-8
username: root
password: 317311
mybatis-plus:
configuration:# sql日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations:
- classpath:mapper/*.xml
4 启动测试
启动springboot哦
页面效果图

导出效果

注意
导入数据时 要保证excel中列名和ExcelStudentDTO一致奥
使用VUE+SpringBoot+EasyExcel 整合导入导出数据的更多相关文章
- 使用Layui、Axios、Springboot(Java) 实现EasyExcel的导入导出(浏览器下载)
实现EasyExcel的导入导出(浏览器下载) 实现三个按钮的功能,但是却花费了一天的时间包括总结. 使用到的技术:springboot layui axios EasyExcel mybatis-p ...
- CRL快速开发框架系列教程九(导入/导出数据)
本系列目录 CRL快速开发框架系列教程一(Code First数据表不需再关心) CRL快速开发框架系列教程二(基于Lambda表达式查询) CRL快速开发框架系列教程三(更新数据) CRL快速开发框 ...
- mysql导入导出数据中文乱码解决方法小结
linux系统中 linux默认的是utf8编码,而windows是gbk编码,所以会出现上面的乱码问题. 解决mysql导入导出数据乱码问题 首先要做的是要确定你导出数据的编码格式,使用mysqld ...
- Android开发笔记:SQLite导入导出数据
SQLite是Android中最方便使用的数据库了,现在看下如何快速的在SQLite中导入导出数据. 首先由于是.NET项目转Android,原有数据库使用的是SQLSERVER,由于项目相同部分结构 ...
- 解决mysql导入导出数据乱码问题
最近在linux上面用mysqldump导出数据,放在windows系统中导入就会出现中文乱码,然后就会导致出现: Unknown MySQL server host和Can't connect to ...
- [转]mysql导入导出数据中文乱码解决方法小结
本文章总结了mysql导入导出数据中文乱码解决方法,出现中文乱码一般情况是导入导入时编码的设置问题,我们只要把编码调整一致即可解决此方法,下面是搜索到的一些方法总结,方便需要的朋友. linux系统中 ...
- oracle中导入导出数据备份数据库
原文:oracle中导入导出数据备份数据库 数据库所在位置 将数据导出到的文件名 用户名 备份数据库 :exp c ...
- PLSQL导入/导出数据方法
PLSQL导入/导出数据方法 PLSQL导入/导出数据方法 以前导数据库信息的时候,总是会先开启sql窗口,把自己手写的建表文件复制进去,然后再导入数据信息. 今天突然懒得去找以前的建表文件,而想用S ...
- oracle10g和oracle11g导入导出数据区别
其中flxuser为用户名,flxuser为密码,file值为导入到数据库中的备份文件. oracle10g和oracle11g导入导出数据的命令方式大有不同: oracle10g导入数据: imp ...
随机推荐
- 详解AOP——用配置文件的方式实现AOP
AOP概念 1.AOP:面向切面(方面)编程,扩展功能不修改源代码实现 AOP原理 AOP采用横向抽取机制,取代了传统纵向继承体系重复性代码 传统的纵向抽取机制: 横向抽取机制: AOP操作术语 1. ...
- SpirngMVC源码分析
分析过程 通过 前端控制器源码 分析 SpringMVC 的执行过程 前端控制器在 web.xml 文件中的配置 <!-- springmvc 前端控制器 --> <servlet& ...
- Ubuntu 18.04 磁盘根目录在线扩容 & 修改分区 inode 数量
Ubuntu 18.04 磁盘根目录在线扩容 & 修改分区 inode 数量 Ubuntu 作为服务器系统使用的时候,系统盘的空间可能并不是很充裕,apt apt 着,根目录就满了.诚然, ...
- 使用css实现任意大小,任意方向, 任意角度的箭头
使用css实现任意大小,任意方向, 任意角度的箭头 网页开发中,经常会使用到 下拉箭头,右侧箭头 这样的箭头. 一般用css来实现: { display: inline-block; margin: ...
- Head标签里面的dns-prefetch,preconnect,prefetch和prerender
开始 今天突然心血来潮想起前端性能优化的问题,这基本是老生常谈的事情了,面试随便都能说上几个,但是还是有点疑问:就是Head标签了,记忆中Head可是藏龙卧虎,各种技能都有,当然这些不可能都一一记住, ...
- 如何使用Flannel搭建跨主机互联的容器网络
当您将多台服务器节点组成一个Docker集群时,需要对集群网络进行设置,否则默认情况下,无法跨主机容器互联,接下来我们首先分析一下原因. 跨主机容器互联 下图描述了一个简单的集群网络,在该集群内,有两 ...
- MVVM模式-数据的双向绑定
- 前端实现导出excel
结果: 将网页上拿到的数据导出成excel文件 实现: HTML代码 <div> <button type="button" onclick="expo ...
- caioj 1000: [视频]整数运算[水题]
题目大意:输入两个整数a和b,输出他们的和. 题解:水题不用题解,简单看一下就知道了-- 代码: #include <cstdio> int a, b; int main() { whil ...
- Java报错: A component required a bean of type 'com.sirifeng.testmybatis.mapper.BookMapper' that could not be found.
在学习Spring-boot-mybatis时,报错A component required a bean of type 'com.sirifeng.testmybatis.mapper.BookM ...