excel-spring-boot-starter是一个基于Java的简单、省内存的读写Excel的开源项目。在尽可能节约内存的情况下支持读写百M的Excel。
64M内存1分钟内读取75M(46W行25列)的Excel,当然还有急速模式能更快,但是内存占用会在100M多一点
spring boot stater依赖
方便在 web 环境下使用 easyexcel ,已上传至 maven 仓库。源码地址:excel-spring-boot-starter
<dependency>
<groupId>com.XXX.excel</groupId>
<artifactId>excel-spring-boot-starter</artifactId>
<version>0.4.0</version>
</dependency>
使用方法
只需要在 Controller 层返注入对应的表格的实体即可,增加 @RequestExcel注解即可、
/**
* @param dataList 使用 @RequestExcel 声明注入的 List
* @param bindingResult 获取excel 校验失败的数据
* @return
*/
@PostMapping
public String req(@RequestExcel List<DemoData> dataList, BindingResult bindingResult) {
// 获取失败的数据
Map<Long, Set<ConstraintViolation<DemoData>>> errorMap = (Map<Long, Set<ConstraintViolation<DemoData>>>) bindingResult.getTarget();
return "success";
}
使用注解 @ExcelProperty 指定实体对应 excel列 (序号从0开始),当然也可以指定 @ExcelProperty(“列标题”) 的形式使用。
@Data
public class DemoData {
@NotBlank(message = "用户名字段不能为空")
@ExcelProperty(index = 0)
private String username;
@NotBlank(message = "密码字段不能为空")
@ExcelProperty(index = 1)
private String password;
}
postman 调用测试
前端上传代码
新增导入按钮
<el-button
type="text"
size="small"
icon="el-icon-download"
@click="handleImport(scope.row, scope.index)"
>导入
</el-button>
导入对话框
<!-- 导入对话框 -->
<el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
<el-upload
ref="upload"
:limit="1"
accept=".xlsx, .xls"
:headers="upload.headers"
:action="upload.url"
:disabled="upload.isUploading"
:on-progress="handleFileUploadProgress"
:on-success="handleFileSuccess"
:auto-upload="false"
drag
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处,或
<em>点击上传</em>
</div>
</el-upload>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitFileForm">确 定</el-button>
<el-button @click="upload.open = false">取 消</el-button>
</div>
</el-dialog>
初始化导入参数
import store from "@/store";
export default {
name: "sys-file",
data() {
return {
upload: {
open: false,
title: "",
isUploading: false,
headers: { Authorization: "Bearer " + store.getters.access_token },
url: "/admin/user/importExcel"
},
};
}
}
导入方法
handleImport() {
this.upload.title = "用户导入";
this.upload.open = true;
},
// 文件上传中处理
handleFileUploadProgress() {
this.upload.isUploading = true;
},
// 文件上传成功处理
handleFileSuccess() {
this.upload.open = false;
this.upload.isUploading = false;
this.$refs.upload.clearFiles();
this.$message.success("导入成功");
this.getList(this.page);
},
// 提交上传文件
submitFileForm() {
this.$refs.upload.submit();
}