public string Create(BusiReq br) { try { var ls = dbContext.BusiReqs.ToList(); // ProjID+BusiReqNo重复的不导入 if (ls.Find(a => a.BRProjID == br.BRProjID && a.BusiReqNo == br.BusiReqNo) != null) { return "<p class='alert alert-danger'>出错了: 记录已存在,不允许重复添加!" + "</p>"; } dbContext.BusiReqs.Add(br); dbContext.SaveChanges(); return Constants.AJAX_CREATE_SUCCESS_RETURN; } catch (Exception e1) { return "<p class='alert alert-danger'>出错了: " + e1.Message + "</p>"; } }
public ActionResult Import(HttpPostedFileBase file, int BRProjID) { if (file == null) { ViewBag.Msg = "<p class='alert alert-danger'>未获取到文件</p>"; } else { // 判断文件夹是否存在,不存在则创建文件夹 var dir = HttpContext.Server.MapPath("~/Upload/temp"); if (Directory.Exists(dir) == false)//如果不存在就创建file文件夹 { Directory.CreateDirectory(dir); } string filePath = Path.Combine(dir, Path.GetFileName(file.FileName)); try { file.SaveAs(filePath); // 读取Excel文件 FileInfo excelFile = new FileInfo(filePath); using (ExcelPackage ep = new ExcelPackage(excelFile)) { ExcelWorksheet worksheet = ep.Workbook.Worksheets[1]; //int colStart = worksheet.Dimension.Start.Column; //工作区开始列 //int colEnd = worksheet.Dimension.End.Column; //工作区结束列 int rowStart = worksheet.Dimension.Start.Row; //工作区开始行号 int rowEnd = worksheet.Dimension.End.Row; //工作区结束行号 var ls = dbContext.BusiReqs.ToList(); for (int row = rowStart + 1; row <= rowEnd; row++) { // 第一列为空则结束 if (worksheet.Cells[row, 1] == null) break; string busiReqNo = worksheet.Cells[row, 1].GetValue<string>(); // ProjID+BusiReqNo重复的不导入 if (ls.Find(a => a.BRProjID == BRProjID && a.BusiReqNo == busiReqNo) != null) { continue; } BusiReq br = new BusiReq(); // 按列赋值 br.BRProjID = BRProjID; br.BusiReqNo = busiReqNo; br.BusiReqName = worksheet.Cells[row, 2].GetValue<string>(); br.Desc = worksheet.Cells[row, 3].GetValue<string>(); // 创建日期若为空则记录为当前时间 string createDate = worksheet.Cells[row, 4].GetValue<string>(); DateTime tmp = new DateTime(); if (!string.IsNullOrEmpty(createDate) && DateTime.TryParse(createDate, out tmp)) { br.CreateDate = tmp; } else { br.CreateDate = DateTime.Now; } br.Stat = worksheet.Cells[row, 5].GetValue<string>(); dbContext.BusiReqs.Add(br); } // 保存 int realNum = dbContext.SaveChanges(); string s = string.Format("<p class='alert alert-success'>《{0}》处理成功!共{1}条数据,实际导入{2}条数据</p>", file.FileName, rowEnd - rowStart, realNum); ViewBag.Msg = s; } } catch (Exception e1) { ViewBag.Msg = "<p class='alert alert-danger'>出错了: " + e1.Message + "</p>"; } finally { // 完成后删除文件 if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } } } List<BusiReqProj> brProjLs = dbContext.BusiReqProjs.ToList(); ViewBag.BRProjLs = new SelectList(brProjLs, "BRProjID", "BRProjName"); return View(); }
public string Edit(BusiReq br) { try { dbContext.Entry(br).State = System.Data.Entity.EntityState.Modified; dbContext.SaveChanges(); return Constants.AJAX_EDIT_SUCCESS_RETURN; } catch (Exception e1) { return "<p class='alert alert-danger'>出错了: " + e1.Message + "</p>"; } }