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", "上傳成功");
}