一.Vue前端部分
前端用formData实现文件上传,也可以用Element-ui封装好的组件
具体参考:Upload上传
<el-button type="primary" plain size="mini" @click="upload()">
文件上传
</el-button>
upload() {
const that = this;
const fileType = ['xls', 'xlsx', 'et']
const inputFile = document.createElement("input")
inputFile.type = "file"
inputFile.style.display = "none"
document.body.appendChild(inputFile)
inputFile.click()
inputFile.addEventListener("change", function () {
const file = inputFile.files[0];
const msg = file.name.substring(file.name.lastIndexOf('.') + 1)
if (!fileType.includes(msg)) {
that.$message.warning("上传的文件格式只能是,xls,xlsx,et");
document.body.removeChild(inputFile);
return false;
}
const formData = new FormData();
formData.append("file", file);
//请求后端接口
XXX(formData).then(res => {
if (res.code === 200) {
that.$message.success("上传成功")
} else {
that.$message.error("上传失败")
}
})
})
}
二.后端部分
1.需要在MAVEN中先导入easy-excel依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.2.0</version>
</dependency>
2.创建Excel和对应的POJO
注意:如果 使用了lombok的话,一定要设置@Accessors(chain = false),不然链式调用可能会导致无法赋值,Bean为空的情况@ExcelProperty()的属性对应excel标题行内容。
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = false) // 设置 chain = false
public class ParkDTO {
@ExcelProperty("停车场")
private String parkName;
@ExcelProperty("车位号")
private String parkNo;
@ExcelProperty("车牌号码")
private String carNo;
@ExcelProperty("车辆类型")
private String carType;
}
3.编写接口用来接收请求
MultipartFile接收参数是spring类型,代表HTML中form data方式上传的文件,包含二进制数据+文件名称。
@PostMapping("import-excel")
public CommonResult importExcel(@RequestParam("file") MultipartFile file) {
try {
List<ParkDTO> data
= EasyExcel.read(file.getInputStream(), ParkDTO.class, null)
.autoCloseStream(false)
.doReadAllSync();
//控制台打印
data.forEach(reqDTO-> System.out.println(reqDTO));
} catch (IOException e) {
log.error("导入失败:"+e);
}
return success("导入成功");
}
控制台打印结果