1.使用上传文件组件 el-upload
<el-popover placement="bottom" width="200" trigger="click">
<div class="popover-download">
<p class="download-tip"><a href="./static/example/themes.xlsx">请下载模板,根据模板上传</a></p>
<el-upload class="upload-demo"
action="file/local/resTemplate"
:data="uploadData"
:before-upload="beforeUpload" multiple>
<el-button type="primary">导入Excel</el-button>
</el-upload>
</div>
<el-button slot="reference">
<i class="icon down-all"></i>
<span class="text">导入实体表</span>
</el-button>
</el-popover>
2.带参数:
uploadData: {
atalogId: "",
type:"2"
},
3.校验方法:
beforeUpload(file) {
this.uploadData.catalogId = this.treeNode.catalogId;
if(this.uploadData.catalogId == null){
this.$message.error('请先选择分类!')
}
let filename = file.name
let arr = filename.split('.')
if (arr[1] !== 'xls' && arr[1] !== 'xlsx') {
this.$message.error('上传文件只能是 excel/xls 格式!')
return false
}
return arr
},
4.后台接收
@PostMapping(value = "/local/resTemplate", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public RetInfo importMetaEntityAndAttr(@RequestParam("file") MultipartFile file,
@RequestParam("catalogId")String catalogId,
@RequestParam("type")String type) {
if (file.isEmpty()) {
return RetInfo.error(400,"文件内容为空");
}
String fileName = file.getOriginalFilename();
String rawFileName = StrUtil.subBefore(fileName, ".", true);
String fileType = StrUtil.subAfter(fileName, ".", true);
if (!fileType.equals("xls")&&!fileType.equals("xlsx")){
return RetInfo.error(450,"上传文件只能是 excel/xls 格式!");
}
String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current(false) + "." + fileType;
try {
file.transferTo(new File(localFilePath));
} catch (IOException e) {
log.error("【文件上传至本地】失败,绝对路径:{}", localFilePath);
return RetInfo.error(500, "文件上传失败");
}
log.info("【文件上传至本地】绝对路径:{}", localFilePath);
/**
* 指定列的下标或者列名
*
* <p>
* 1. 创建excel对应的实体对象,并使用{@link ExcelProperty}注解. 参照{@link TableInfo}
* <p>
* 2. 由于默认一行行的读取excel,所以需要创建excel一行一行的回调监听器,参照{@link TableInfoListener}
* <p>
* 3. 直接读即可
*/
Map<String,Object> parmas = new HashMap<>();
parmas.put("catalogId",catalogId);
parmas.put("type",type);
try {
EasyExcel.read(localFilePath, TableAttrInfo.class,new TableInfoListener(parmas,modelEntityService)).sheet().doRead();
}catch (Exception e){
RetInfo.error().put("message", "请检查表格中的参数类型是否正确");
}
return RetInfo.ok().put("code", 200).put("message", "上传成功");
}