1. 程式人生 > 其它 >上傳資料、下載模板檔案解決方案(前端:antd;後端:.Net Core WebAPI)

上傳資料、下載模板檔案解決方案(前端:antd;後端:.Net Core WebAPI)

 

一、Excel 模板下載

  通過靜態檔案下載。

將模板檔案放在根目錄的 public 資料夾下備用。

下載事件方法如下:(通過臨時生成一個 a 標籤,觸發後再移除)

    downLoadExcelModel = () => {
      var a = document.createElement("a");
      a.href = "./ModelName.xlsx";
      a.download = "模板檔名.xlsx";
      a.style.display = "none";
      document.body.appendChild(a);
      a.click();
      a.remove();
    };

二、上傳 Excel 表格

 通過 Upload 控制元件上傳目標檔案,然後呼叫後臺介面進行資料處理:(部分簡單的變數處理省略)

 1 //先引入 axios
 2     import axios from 'axios';//npm install axios
 3     import { UploadOutlined } from '@ant-design/icons';
 4 
 5 //控制元件上傳事件
 6     uploadDictList=({file, fileList})=>{
 7       console.log("file.status",file.status);
8 if (file.status === "done") { 9 const formData = new FormData() 10 formData.append('file', fileList[fileList.length - 1].originFileObj); 11 console.log("formData:",formData); 12 axios({ 13 method: 'post', 14 url: '/api/List?paraname='+this
.state.typecode,//配置訪問介面 15 data: formData, 16 headers: { "Content-Type": "multipart/form-data"} 17 }).then(({data}) => { 18 console.log("baxk-data:",data); 19 if(data.code==200) 20 message.success(`上傳成功!(成功/總數:${data.desc})`) 21 else 22 message.error("上傳失敗,請稍後重試!"); 23 }).catch((err) =>{ 24 console.log(err); 25 message.error("上傳失敗,請稍後重試!"); 26 }) 27 } 28 else if (file.status === "error") { 29 message.error(`上傳失敗,請稍後重試!${file.name}`); 30 } 31 } 32 33 //控制元件 34 <Upload 35 fileList={fileList} 36 showUploadList={false} 37 onChange={this.uploadDictList} 38 > 39 <Button disabled={uploadable} type="primary" icon={<UploadOutlined />} style={{margin:"20px 20px 20px 0"}}>上傳資料項</Button> 40 </Upload>

 三、.Net Core 3.0 WebAPI 檔案接收與解析

主要就是 IFormCollection 來接收傳入檔案。

 1     using Dapper;
 2     using Microsoft.AspNetCore.Cors;
 3     using Microsoft.AspNetCore.Http;
 4     using Microsoft.AspNetCore.Mvc;
 5     using NPOI.HSSF.UserModel;
 6     using NPOI.SS.UserModel;
 7     using NPOI.XSSF.UserModel;
 8     using System;
 9     using System.Collections.Generic;
10     using System.Data;
11     using System.IO;
12     using System.Linq;
  1     [HttpPost]
  2     public BackDataModel UploadddList(string ddtype, IFormCollection file)
  3     {
  4         var fileobj = file.Files[0];
  5         string filename = Path.GetFileName(fileobj.FileName);
  6         var filesize = fileobj.Length;//獲取上傳檔案的大小單位為位元組byte
  7         string fileType = System.IO.Path.GetExtension(filename);//獲取上傳檔案的副檔名
  8         long maxsize = 4000 * 1024;//定義上傳檔案的最大空間大小為4M
  9         if (filesize >= maxsize)
 10             return new BackDataModel() { Code = 201, Desc = $"匯入失敗,表格檔案必須小於(4M)。" };
 11         var filestream = fileobj.OpenReadStream();
 12         DataTable dt = new DataTable();
 13         ISheet sheet = null;
 14         IWorkbook workbook = null;
 15         if (fileType == ".xlsx")//2007以上版本excel
 16             workbook = new XSSFWorkbook(filestream);
 17         else if (fileType == ".xls")//2007以下版本excel
 18             workbook = new HSSFWorkbook(filestream);
 19         else
 20             throw new Exception("傳入的不是Excel檔案!");
 21         sheet = workbook.GetSheetAt(0);//取第一個 sheet
 22         var idddModellist_insert = new List<IdddModel>();
 23         int countall = 0;
 24         if (sheet != null)
 25         {
 26             IRow firstRow = sheet.GetRow(0);//首行值設定為表頭
 27             int cellCount = firstRow.LastCellNum;
 28             if (cellCount != 6 || firstRow.Cells[0].StringCellValue != "程式碼" || firstRow.Cells[1].StringCellValue != "名稱" || firstRow.Cells[2].StringCellValue != "備註1"
 29                 || firstRow.Cells[3].StringCellValue != "備註2" || firstRow.Cells[4].StringCellValue != "備註3" || firstRow.Cells[5].StringCellValue != "備註4")
 30             {
 31                 return new BackDataModel() { Code = 201, Desc = $"匯入失敗,請按照‘模板’填值後重試!" };
 32             }
 33             for (int i = firstRow.FirstCellNum; i < cellCount; i++)
 34             {
 35                 ICell cell = firstRow.GetCell(i);
 36                 if (cell != null)
 37                 {
 38                     string cellValue = cell.StringCellValue.Trim();
 39                     if (!string.IsNullOrEmpty(cellValue))
 40                     {
 41                         DataColumn dataColumn = new DataColumn(cellValue);
 42                         dt.Columns.Add(dataColumn);
 43                     }
 44                 }
 45             }
 46             DynamicParameters dynamicParameters = new DynamicParameters();
 47             dynamicParameters.Add("@typename", ddtype);
 48             string sql_getddinfo = "select * from aa where g>0";
 49             var ddinfolist = db.factory.Query<IdddModel>(sql_getddinfo, dynamicParameters).ToList();
 50             int ddnumber = 1;
 51             for (int j = sheet.FirstRowNum + 1; j <= sheet.LastRowNum; j++)//遍歷行
 52             {
 53                 var idddModel = new IdddModel();
 54                 IRow row = sheet.GetRow(j);
 55                 if (row == null || row.Cells.Count != 6 ||
 56                     ((row.GetCell(0) == null || row.GetCell(0).StringCellValue.Length == 0) && (row.GetCell(1) == null || row.GetCell(1).StringCellValue.Length == 0)))//值不為空
 57                 {
 58                     continue;
 59                 }
 60                 countall++;
 61                 if (row.GetCell(0) != null && row.GetCell(1).CellType == CellType.String)
 62                 {
 63                     idddModel.ddcode = row.GetCell(0).ToString();
 64                 }
 65                 if (row.GetCell(1) != null && row.GetCell(1).CellType == CellType.String)
 66                 {
 67                     idddModel.ddname = row.GetCell(1).ToString();
 68                 }
 69                 if (row.GetCell(2) != null)
 70                 {
 71                     idddModel.Remark1 = row.GetCell(2).ToString();
 72                 }
 73                 if (row.GetCell(3) != null)
 74                 {
 75                     idddModel.Remark2 = row.GetCell(3).ToString();
 76                 }
 77                 if (row.GetCell(4) != null)
 78                 {
 79                     idddModel.Remark3 = row.GetCell(4).ToString();
 80                 }
 81                 if (row.GetCell(5) != null)
 82                 {
 83                     idddModel.Remark4 = row.GetCell(5).ToString();
 84                 }
 85                 if (ddinfolist.Where(dd => dd.ddcode == idddModel.ddcode && dd.ddname == idddModel.ddname)
 86                 {
 87                     idddModel.ddtypecode = ddinfolist?[0].ddtypecode;
 88                     idddModel.ddtypename = ddinfolist?[0].ddtypename;
 89                     idddModel.ID = Guid.NewGuid().ToString();
 90                     idddModel.Snumber = ddinfolist.Count + ddnumber;
 91                     idddModel.Insert_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
 92                     idddModel.Update_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
 93                     idddModel.ff = 1;
 94                     idddModellist_insert.Add(idddModel);
 95                     ddnumber++;
 96                 }
 97             }
 98             string sql_insertdd = $"insert into ";
 99             int backnum = db.factory.Execute(sql_insertdd, idddModellist_insert);
100             if (backnum != 1 && idddModellist_insert.Count > 0)
101                 return new BackDataModel() { Code = 201, Desc = $"資料儲存不成功,請重新整理列表確認!" };
102         }
103         else
104         {
105             return new BackDataModel() { Code = 201, Desc = $"匯入失敗,未取到表格中資料!" };
106         }
107         return new BackDataModel() { Code = 200, Desc = $"{idddModellist_insert.Count}/{countall}" };
108     }

以上程式碼已驗證可用,若有疑問,請留言討論。