vue+elementui 批量上傳excel webapi后台接收並保存到數據庫


效果圖:

 

 

 

 

 上傳窗口:

 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         }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM