效果图:
上传窗口:
1 <el-dialog title="上传部件" :visible.sync="isEditWinShow" custom-class="customWidth" :close-on-click-modal="false"> 2 <el-form label-width="100px"> 3 <el-row> 4 <el-col :span="24"> 5 <el-upload ref="upload" action="#" :limit="200" multiple accept=".xls,.xlsx" :on-change="handleChange" 6 :on-remove="handleRemove" :on-exceed="handleExceed" :file-list="fileList" :http-request="uploadFile" 7 :auto-upload="false"> 8 <el-button slot="trigger" type="primary" size="small" align="right">选取文件</el-button> 9 </el-button> 10 <el-button type="success" style="margin-left: 100px;" size="small" @click="submitUpload">上传到服务器</el-button> 11 <div slot="tip" class="el-upload__tip">只能上传xlsx文件,且不超过700KB</div> 12 </el-upload> 13 </el-col> 14 </el-row> 15 </el-form> 16 </el-dialog>
1 // 导入exel 2 async importExcel() { 3 this.isEditWinShow = true; 4 }, 5 // 上传文件 6 uploadFile(file) { 7 this.fileData.append('files', file.file); 8 }, 9 submitUpload() { 10 const loading = this.$loading({ 11 lock: true, 12 text: '数据提取中,请稍后', 13 spinner: 'el-icon-loading', 14 background: 'rgba(0, 0, 0, 0.7)' 15 }); 16 if (this.fileList.length === 0) { 17 this.$message({ 18 message: '请先选择文件', 19 type: 'warning' 20 }); 21 } else { 22 const isLt700K = this.fileList.every(file => file.size / 1024 / 1024 / 1024 < 700); 23 if (!isLt700K) { 24 this.$message.error('请检查,上传文件大小不能超过700KB!'); 25 } else { 26 var formData = new FormData(); // 用FormData存放上传文件 27 this.fileList.forEach(file => { 28 formData.append('partsInfoFile', file.raw, file.raw.name); 29 })
//向webapi发起请求,等待后台接收 30 axios.post(axiosbaseUrl_ex + '/PartsInfo/upload/', formData, { 31 headers: { 32 'Content-Type': 'multipart/form-data' 33 } 34 }) 35 .then((response) => { 36 if (response.status == "200") { 37 setTimeout(() => { 38 loading.close(); 39 this.getPartsList(); 40 this.$message({ 41 type: 'success', 42 message: '导入成功!' 43 }); 44 this.getPartsList(); 45 this.fileList = []; 46 this.fileData = ""; 47 this.isEditWinShow = false; 48 this.isLoading = false; 49 }, 1000); 50 } else { 51 this.$message({ 52 type: 'error', 53 message: '导入失败,请检查模板是否正确' 54 }); 55 this.isLoading = false; 56 } 57 }, 58 error => { 59 loading.close(); 60 this.$message.error('系统异常,请稍后再试'); 61 return Promise.reject(error); 62 } 63 ) 64 } 65 } 66 }, 67 //移除 68 handleRemove(file, fileList) { 69 this.fileList = fileList; 70 }, 71 // 选取文件超过数量提示 72 handleExceed(files, fileList) { 73 this.$message.warning(`当前限制选择200个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`); 74 }, 75 //监控上传文件列表 76 handleChange(file, fileList) { 77 let existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name); 78 if (existFile) { 79 this.$message.error('当前文件已经存在!'); 80 fileList.pop(); 81 } 82 this.fileList = fileList; 83 }
fileData: '', // 文件上传数据(多文件合一)
fileList: [], // upload多文件数组
以上为data中声明的变量
webapi如何接收:
1 [DescriptionName("上传部件信息")] 2 [HttpPost, Route("PartsInfo/upload")] 3 public ResultModel UploadPartsInfo() 4 { 5 ResultModel res = new ResultModel(); 6 HttpFileCollection fileList = System.Web.HttpContext.Current.Request.Files; 7 // 判断是否有上传的文件 8 if (fileList == null || fileList.Count == 0) 9 { 10 res.message = "请先选择要上传的文件!"; 11 return res; 12 } 13 14 #region 将上传的所有的excel文件保存在一个临时文件夹中 15 string dicName = string.Format("PartsInfo_{0}", DateTime.Now.ToString("yyyyMMddHHmmss")); 16 string filePath = TempFilePath + dicName; 17 FileHelper.CreateDirectory(filePath); 18 for (int i = 0; i < fileList.Count; i++) 19 { 20 HttpPostedFile uploadFile = fileList[i]; 21 // 判断文件的格式是否是.xlsx或者.xls 22 string suffix = Path.GetExtension(uploadFile.FileName); 23 List<string> fileTypeList = new List<string>() { ".xlsx", ".xls" }; 24 if (!fileTypeList.Contains(suffix)) 25 { 26 res.message = "上传文件的后缀名必须是“.xlsx”或!“.xls”"; 27 return res; 28 } 29 string newFileName = string.Format("{0}/{1}", filePath, uploadFile.FileName); 30 uploadFile.SaveAs(newFileName); 31 } 32 #endregion 33 34 #region 读取存储的临时文件并保存入库 35 try 36 { 37 string[] tempfileList = FileHelper.GetFileNames(filePath); 38 foreach (var file in tempfileList) 39 { 40 Thread t = new Thread(this.ReadExcel); 41 t.Start(file); 42 } 43 res = new ResultModel() 44 { 45 status = "1", 46 message = "导入成功" 47 }; 48 } 49 catch (Exception) 50 { 51 res = new ResultModel() 52 { 53 status = "-1", 54 message = "导入失败" 55 }; 56 } 57 58 #endregion 59 60 return res; 61 }
多线程读取临时文件
1 string errMsg = string.Empty; 2 3 /// <summary> 4 /// 读取某个excel文件 5 /// </summary> 6 /// <param name="filePath"></param> 7 private void ReadExcel(object filePath) 8 { 9 try 10 { 11 HSSFWorkbook workbook; 12 using (FileStream file = new FileStream(filePath.ToString(), FileMode.Open, FileAccess.ReadWrite)) 13 { 14 workbook = new HSSFWorkbook(file); 15 file.Close(); 16 } 17 if (workbook.NumberOfSheets < 2) 18 { 19 errMsg = "请检查上传的部件数据是否正确"; 20 return; 21 } 22 var sheet = workbook.GetSheetAt(0); 23 24 //读取装置序列号 25 string indexNum = sheet.GetRow(2).GetCell(3).StringCellValue; 26 if (string.IsNullOrEmpty(indexNum)) 27 { 28 //如果第3行第4个单元格 的值是空的话,再读取第5行第4个单元格的值作为装置序列号 29 indexNum = sheet.GetRow(4).GetCell(3).StringCellValue; 30 } 31 //根据读取的装置序列号获取设备信息 32 BizBaseInfoBll baseInfoBll = new BizBaseInfoBll(); 33 var baseInfo = baseInfoBll.GetByIndexNum(indexNum); 34 List<BizPartInfo> newList = new List<BizPartInfo>(); 35 if (baseInfo != null) 36 { 37 var colSheet = workbook.GetSheetAt(1); 38 //获取模板的内容区域 39 int rowCount = colSheet.LastRowNum; 40 BizPartInfo model = new BizPartInfo(); 41 //从excel模板的第9行开始读取 42 for (int i = 1; i <= rowCount; i++) 43 { 44 //获取模板的第三列数据 作为部件名称 45 ICell cell = colSheet.GetRow(i).GetCell(2); 46 if (cell == null) 47 { 48 break; 49 } 50 //获取模板的第四列数据 作为部件序列号 51 ICell cell4 = colSheet.GetRow(i).GetCell(3); 52 ICell cell2 = colSheet.GetRow(i).GetCell(1); 53 if (cell4.CellType == CellType.Formula) 54 { 55 cell4.SetCellType(CellType.String); 56 } 57 string cell4Str = cell4.StringCellValue; 58 if (cell2.CellType == CellType.Numeric) 59 { 60 cell2.SetCellType(CellType.String); 61 } 62 string cell2Str = cell2.StringCellValue; 63 int partNo = 0; 64 Int32.TryParse(cell2Str, out partNo); 65 //SysUser curUser = CommonUtil.GetLoginUser(); 66 if (cell != null && !string.IsNullOrEmpty(cell.StringCellValue)) 67 { 68 //将读取的模板数据组装成部件信息 69 model = new BizPartInfo() 70 { 71 MachineIndex = indexNum, 72 IsDel = false, 73 PartName = cell.StringCellValue, 74 PartNo = partNo, 75 PartIndex = cell4Str, 76 // CreateUser = curUser.UserId, 77 CreateDate = DateTime.Now 78 }; 79 newList.Add(model); 80 } 81 } 82 } 83 partsInfoBll.ImportPart(indexNum, newList); 84 } 85 catch (Exception) 86 { 87 } 88 }