1. 服务端操作
1.1 导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
1.2 创建导入实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "clothes")
public class Clothes {
@TableId(type = IdType.AUTO)
private Integer id;
@ExcelProperty(value = "编号")
private String number;
@ExcelProperty(value = "类型")
private String type;
@ExcelProperty(value = "规模型号")
private String model;
@ExcelProperty(value = "尺寸")
@TableField(value = "size_name")
private String size;
@ExcelProperty(value = "颜色")
@TableField(value = "color_name")
private String color;
@ExcelProperty(value = "生产日期")
@TableField(value = "production_date")
private String productionDate;
@ExcelProperty(value = "生产商")
private String manufacturer;
@ExcelProperty(value = "已清洗次数")
@TableField(value = "times_cleaned")
private Integer timesCleaned;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
private Integer status;
@TableField(value = "scrap_way")
private Integer scrapWay;
}
说明:@ExcelProperty中value值为导入excel表头名称
1.3 controller拦截
/**
* 导入excel
*/
@RequiredClothesLog(ClassObject.COLTHES_IMPORT)
@PostMapping("/import")
public Result<List<String>> excelImport(MultipartFile file) throws ParseException {
try {
// 把前端传的文件转化成流
InputStream inputStream = file.getInputStream();
// 读取表格数据,转化成对象
List<Clothes> needDtos = EasyExcel.read(file.getInputStream()).head(Clothes.class).sheet().doReadSync();
// 保存到数据库
boolean result = clothesExcelService.saveBatch(needDtos);
inputStream.close();
} catch (Exception e) {
log.error("导入数据错误", e);
return Result.failed(e.getMessage());
}
return Result.success(null);
}
2. vue客户端操作
2.1 使用ele组件
<el-tab-pane label="Excel导入"
><el-upload
:limit="limitNum"
class="upload-demo"
drag
multiple
name="file"
:auto-upload="false"
accept=".xlsx"
:action="UploadUrl()"
:before-upload="beforeUploadFile"
:on-change="fileChange"
:on-exceed="exceedFile"
:on-success="handleSuccess"
:on-error="handleError"
:on-remove="removeFile"
:file-list="fileList"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处,或<em>点击上传</em>
</div>
<div class="el-upload__text">支持拓展名 xlsx</div>
<div class="el-upload__tip" slot="tip">
上传完成后可以在页面查看导入的列表
</div> </el-upload
><el-button
size="small"
type="primary"
@click="uploadFile"
v-show="fileList.length != 0"
>立即上传</el-button
></el-tab-pane
>
2.2 js处理
data(){
return {
limitNum: 1, // 上传excell时,同时允许上传的最大数
fileList: [],
}
}
method:{
// 文件超出个数限制时的钩子
exceedFile(files, fileList) {
this.$message.warning(
`只能选择 ${this.limitNum} 个文件,当前共选择了 ${
files.length + fileList.length
} 个`
);
},
// 文件状态改变时的钩子
fileChange(file, fileList) {
console.log(file.raw);
this.fileList.push(file.raw);
console.log(this.fileList);
},
removeFile(file, fileList) {
this.fileList = [];
},
// 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传
beforeUploadFile(file) {
console.log("before upload");
console.log(file);
let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
let size = file.size / 1024 / 1024;
if (extension !== "xlsx") {
this.$message.warning("只能上传后缀是.xlsx的文件");
}
if (size > 10) {
this.$message.warning("文件大小不得超过10M");
}
},
// 文件上传成功时的钩子
handleSuccess(res, file, fileList) {
this.$message.success("文件上传成功");
},
// 文件上传失败时的钩子
handleError(err, file, fileList) {
this.$message.error("文件上传失败");
},
UploadUrl: function () {
// 因为action参数是必填项,我们使用二次确认进行文件上传时,直接填上传文件的url会因为没有参数导致api报404,所以这里将action设置为一个返回为空的方法就行,避免抛错
return "";
},
uploadFile() {
if (this.fileList.length === 0) {
this.$message.warning("请上传文件");
} else {
let form = new FormData();
console.log(this.fileList)
console.log(form)
form.append("file", this.fileList[0]);
console.log(form.get('file'))
this.$axios({
method: "post",
url: "/clothes/import",
// 请求头比较重要
headers: {
"Content-type": "multipart/form-data",
},
data: form,
}).then(
(res) => {
this.fileList=[]
if (res.data.code == 200) {
this.$message.success("文件上传成功");
}
else {
this.$notify({
title: '提示',
message: res.data.msg,
duration: 0,
type: 'warning'
});
}
},
(err) => {
this.fileList=[]
}
);
}
},
}