common-excel 模块基于 Easyexcel 实现 Excel 的读写。
EasyExcel 是一个基于 Java 的简单、省内存的读写 Excel 的开源项目。在尽可能节约内存的情况下支持读写百 M 的 Excel。 64M 内存 1 分钟内读取 75M(46W 行 25 列)的 Excel,当然还有急速模式能更快,但是内存占用会在 100M 多一点

引入依赖
<dependency><groupId>com.pig4cloud.excel</groupId><artifactId>excel-spring-boot-starter</artifactId></dependency>
定义导入导出实体
public class UserExcelVO {@ExcelProperty("用户编号")private Integer userId;@NotBlank(message = "用户名不能为空")@ExcelProperty("用户名")private String username;}
导出
后端代码
- Controller 接口直接返回 List 元素即可,这里特别注意的时 接口上需要声明 @ResponseExcel 注解
@ResponseExcel@GetMapping("/export")public List<UserExcelVO> export(UserDTO userDTO) {return userService.listUser(userDTO);}
前端页面
- 定义 menuLeft 的卡槽
<template slot="menuLeft"><el-buttonclass="filter-item"plaintype="primary"size="small"icon="el-icon-download"@click="exportExcel">导出</el-button></template>
- 具体的导出事件定义 downBlobFile 已经定义成全局方法,可以直接引用
exportExcel() {this.downBlobFile("/admin/user/export", this.searchForm, "user.xlsx");}
- downBlobFile 方法参数说明 | 参数 | 示例 | 描述 | | —- | —- | —- | | url | /admin/user/export | 请求后端的接口地址 | | params | this.searchForm | 查询参数 | | filename | user.xls | 下载后显示的文件名称 |
导入
后端代码
- Controller 接口使用 @RequestExcel 标记前端 excel 对应的实体列表, BindingResult 用来校验 实体 jsr303 校验失败结果
@PostMapping("/import")public R importUser(@RequestExcel List<UserExcelVO> excelVOList, BindingResult bindingResult) {return userService.importUser(excelVOList, bindingResult);}
- 获取校验结果 ,把不合法数据返回前端回显原因。 其中包括两种不合法(JSR303 不合法数据、自己个性化校验的)
List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();
- JSR 303 通用校验结果

- 个性化校验 通用校验结果

if (CollUtil.isNotEmpty(errorMessageList)) {return R.failed(errorMessageList);}
前端页面
- 定义 menuLeft 的卡槽
<template slot="menuLeft"><el-buttonclass="filter-item"plaintype="primary"size="small"icon="el-icon-upload"@click="$refs.excelUpload.show()">导入</el-button></template>
- 引入组件 ExcelUpload
import ExcelUpload from "@/components/upload/excel";<!--excel 模板导入 --><excel-uploadref="excelUpload"title="用户信息导入"url="/admin/user/import"temp-url="/admin/sys-file/local/user.xlsx"@refreshDataList="refreshChange"></excel-upload>
- excel-upload 组件参数说明 | 参数 | 示例 | 描述 | | —- | —- | —- | | ref | excelUpload | 固定值和上文导入按钮的 ref 绑定值保持一致,不需要修改 | | title | 用户信息导入 | 弹出框标题 | | url | /admin/user/import | 后台接口地址 | | temp-url | /admin/sys-file/excel-temp/user.xlsx | 导入模板下载地址 都是通过此接口下载,模板放在 upms 模块 |


