思路:用戶點擊下載模板按鈕,獲取到excel模板,然后向里面填寫數據保存。from表單提交的時候選擇保存好的excel,實現數據的批量導入過程
先把模板放在服務器的項目目錄下面:如

模板我一般放在:File\download\檢測項目價格導入模板.xls
模板內容如:

下載模板的按鈕只需指向服務器的文件地址,模板會自動下載。
地址如:var FilePath = "http://*********/File/download/檢測項目價格導入模板.xls",但是地址一般不寫死,而是域名是從webConfig文件中獲取的。
例如:<add key="FileServiceAddr" value="http://localhost:8066/"/>
接口如:
/// <summary> /// 下載模板 /// </summary> /// <returns></returns> [HttpGet] [AllowAnonymous] public string DownLoadTemple() { try { //var FilePath = "http://testadmin.hysyzs.com/download/檢測項目價格導入模板.xls"; var FilePath = System.Configuration.ConfigurationManager.AppSettings["FileServiceAddr"].ToString() +"/download/檢測項目價格導入模板.xls"; //var excel = new Aspose.Cells.Workbook(); //打開上傳文件 //excel.Open(FilePath); //var fileMemoryStream = FilePath.Write(ms); //HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); //response.Content = new ByteArrayContent(fileMemoryStream.ToArray()); //response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); //response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") //{ // FileName = "會議簽到匯總表.xls" //}; return FilePath; } catch (Exception e) { return e.ToString(); } }
然后用戶下載后,編輯內容,form表單提交,后台的處理直接上代碼
/// <summary> /// 批量導入價格(form表單方式提交數據) /// </summary> /// <returns></returns> [HttpPost] [AllowAnonymous] public ReturnObject<List<string>> UploadImportPrize() { ReturnObject<List<string>> ret = new ReturnObject<List<string>>(); List<string> errors = new List<string>(); List<string> fails = new List<string>(); string completePath = ""; HttpFileCollection filelist = HttpContext.Current.Request.Files; if (filelist != null && filelist.Count > 0) { for (int i = 0; i < filelist.Count; i++) { HttpPostedFile file = filelist[i]; String Tpath = DateTime.Now.ToString("yyyy-MM-dd") + @"/import/"; string filename = file.FileName; //string FilePath = "D:\\" + Tpath + filename; //
string FilePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/") + Tpath + filename;
//這里應該獲取當前項目路徑地址,再在后面創建文件,如果按上面的注釋掉的寫法,在服務器上沒有找到d盤,則會報錯。
string diPath = Path.GetDirectoryName(FilePath); //獲取到當前目錄的文件夾,沒有就創建 if (!Directory.Exists(diPath)) { Directory.CreateDirectory(diPath); }; try { completePath = FilePath; file.SaveAs(completePath); //生成一個文件目錄,把上傳的文件寫入到目錄中去, var d = ImportPrize(completePath); //然后獲取這個目錄的文件,用DataTable進行讀取,然后解析excel的每行數據,批量寫入到數據庫中 ret.datas = d.datas; ret.isOK = true; ret.errorCode = 0; } catch (Exception ex) { ret.msg = "上傳文件寫入失敗:" + ex.Message; ret.isOK = false; ret.errorCode = 3; } } } else { ret.msg = "上傳的文件信息不存在!"; ret.isOK = false; ret.errorCode = 3; } return ret; }
將excel的數據加載到DataTable中去
/// <summary> /// /// </summary> /// <param name="path"></param> /// <returns></returns> private DataTable ReadExcelToTable(string path) { DataTable result = new DataTable(); Workbook workbook = new Workbook(); workbook.Open(path); Cells cells = workbook.Worksheets[0].Cells; result = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxColumn + 1, false); return result; }
批量寫入數據庫的過程
/// <summary> /// 寫入數據到數據庫 /// </summary> /// <param name="completePath"></param> /// <returns></returns> public ReturnObject<List<string>> ImportPrize(string completePath) { ReturnObject<List<string>> ret = new ReturnObject<List<string>>(); List<string> errors = new List<string>(); List<string> fails = new List<string>(); int succescount = 0; int failcount = 0; try { var a = ReadExcelToTable(completePath).Rows; List<InPrize> list = new List<InPrize>(); if (a.Count > 1) { for (var i = 0; i < a.Count; i++) { if (i == 0) { #region 判斷列名 var col_one = a[i][0].ToString(); if (col_one != "版本") { throw new Exception("格式錯誤,導入文件的第一列應為【版本】!"); } //var col_two = a[i][1].ToString(); //if (col_two != "版本狀態") //{ // throw new Exception("格式錯誤,導入文件的第一列應為【版本狀態】!"); //} var col_three = a[i][1].ToString(); if (col_three != "檢測機構檢測項") { throw new Exception("格式錯誤,導入文件的第一列應為【檢測機構檢測項】!"); } var col_five = a[i][2].ToString(); if (col_five != "區域市場") { throw new Exception("格式錯誤,導入文件的第一列應為【區域市場】!"); } var col_six = a[i][3].ToString(); if (col_six != "區域市場價格") { throw new Exception("格式錯誤,導入文件的第一列應為【區域市場價格】!"); } var col_even = a[i][4].ToString(); if (col_even != "VIP零售價格") { throw new Exception("格式錯誤,導入文件的第一列應為【VIP零售價格】!"); } #endregion } else { //int intType2; var intTypeStr2 = a[i][1].ToString(); //if (!int.TryParse(intTypeStr2, out intType2)) //{ // throw new Exception("格式錯誤,【版本狀態】【第" + (i + 1) + "行】應為整數類型數據!"); //} int intType1; var intStr1 = a[i][1].ToString(); if (!int.TryParse(intStr1, out intType1)) { throw new Exception("格式錯誤,【檢測機構檢測項】【第" + (i + 1) + "行】應為整數類型數據!"); } int intType; var intStr = a[i][2].ToString(); if (!int.TryParse(intStr, out intType)) { throw new Exception("格式錯誤,【區域市場】【第" + (i + 1) + "行】應為整數類型數據!"); } decimal docmoney_int; var docmoney_str = a[i][3].ToString(); if (!decimal.TryParse(docmoney_str, out docmoney_int)) { throw new Exception("格式錯誤,【區域市場價格】【第" + (i + 1) + "行】應為數字類型數據!"); } decimal doczmoney_int; var doczmoney_str = a[i][4].ToString(); if (!decimal.TryParse(doczmoney_str, out doczmoney_int)) { throw new Exception("格式錯誤,【VIP零售價格】【第" + (i + 1) + "行】應為數字類型數據!"); } list.Add(new InPrize() { Version = a[i][0].ToString(), //VersionState = false, DetectionOrgDetectionItemID = intType1, AreaMarketID = intType, Price = docmoney_int, vipPrice = doczmoney_int }); } } #region ListForEach using (YZS_BUSEntities context = new YZS_BUSEntities()) { foreach (var item in list) { var entities = context.Set<區域產品信息>().Where(n => n.檢測機構檢測項.Value == item.DetectionOrgDetectionItemID && n.區域市場.Value == item.AreaMarketID && n.版本狀態.Value == false).ToList(); if (entities.Count() > 0) { fails.Add("檢測項:" + item.DetectionOrgDetectionItemID + "區域市場:" + item.AreaMarketID); failcount++; } else { context.區域產品信息.Add(new 區域產品信息() { 版本 = item.Version, 版本狀態 = false, 檢測機構檢測項 = item.DetectionOrgDetectionItemID, 區域市場 = item.AreaMarketID, 區域市場價格 = item.Price, VIP零售價格 = item.vipPrice }); succescount++; } } context.SaveChanges(); string failRemark = ""; if (failcount > 0) { failRemark = ",失敗的數據:" + string.Join(",", fails); } errors.Add($"成功導入{succescount}條樣本信息!失敗{failcount}條{failRemark}"); } ret.isOK = true; ret.errorCode = 0; ret.msg = ""; ret.count = succescount; ret.datas = errors; #endregion } else { throw new Exception("所選文件格式錯誤,或者未匹配到有效數據!"); } } catch (Exception error) { ret.isOK = false; ret.errorCode = 200; ret.msg = error.Message; ret.count = 0; ret.datas = errors; } return ret; }
實體模型
public class InPrize { /// <summary> ///檢測機構檢測項ID /// </summary> public int DetectionOrgDetectionItemID { get; set; } /// <summary> ///區域市場ID /// </summary> public int AreaMarketID { get; set; } /// <summary> ///價格 /// </summary> public decimal? Price { get; set; } /// <summary> /// vip零售價格 /// </summary> public decimal? vipPrice { get; set; } /// <summary> /// 版本 /// </summary> public string Version { get; set; } ///// <summary> ///// 版本狀態 ///// </summary> //public int? VersionState { get; set; } }

