public IHttpActionResult ImportFood() { HttpFileCollection files = HttpContext.Current.Request.Files; foreach (string key in files.AllKeys) { HttpPostedFile file1 = files[key]; bool exportColumnName = true; Workbook workbook = new Workbook(file1.InputStream); Worksheet worksheet = workbook.Worksheets[0]; Cells cells = worksheet.Cells; string titleformat = "食品类别,食品编号,食品名称,规格,计量单位,价格"; string title = ""; for (int j = 0; j < cells.MaxDataColumn + 1; j++) { title += cells[0, j].StringValue.Trim() + ','; } if (title.Substring(0, title.Length - 1) != titleformat) { return Json(new { success = false, message = "文件不符合格式!你可以下载模板重新导入!" }); } var data = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, exportColumnName); List<fd_food_library> bacth_foodlibrary = new List<fd_food_library>(); List<string> name = (from d in data.AsEnumerable() select d.Field<string>("食品名称")).ToList(); List<string> price = (from d in data.AsEnumerable() select d.Field<string>("价格")).ToList(); foreach (var item in price) { if (!string.IsNullOrEmpty(item)) { decimal num; if (decimal.TryParse(item, out num) == false) { return Json(new { success = false, message = item + "不是数字,请检查后重试!" }); } } } var foodlibrary = _foodlibraryRepository.GetFoodByName(name); var pga = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; pga.Predicates.Add(Predicates.Field<im_item_type>(x => x.state, Operator.Eq, 0)); pga.Predicates.Add(Predicates.Field<im_item_type>(x => x.type, Operator.Eq, "食品")); var foodtype = _itemtypeRepository.GetList(pga).Where(a => a.name != "食品").ToList(); foreach (DataRow item in data.Rows) { if(item["食品名称"].ToString()=="") { return Json(new { success = false, message = data.Rows.IndexOf(item)+1+"行食品名称为空,请检查后重试!" }); } if (name.Where(a => a == item["食品名称"].ToString()).Count() > 1) { return Json(new { success = false, message = item["食品名称"].ToString() + "食品名称有重复,请检查后重试!" }); } var type = foodtype.Where(a => a.name == item["食品类别"].ToString()).FirstOrDefault(); if (type == null) return Json(new { success = false, message = item["食品类别"].ToString() + "类别不存在,请检查后重试!" }); var food = foodlibrary.Where(a => a.name == item["食品名称"].ToString()).FirstOrDefault(); if (food == null) { bacth_foodlibrary.Add(new fd_food_library { id = Guid.NewGuid().ToString(), type_id = type.id, type_name = type.name, number = item["食品编号"].ToString(), name = item["食品名称"].ToString(), unit = item["计量单位"].ToString(), month = 0, warn_quantity = 0, state = 0, price = item["价格"].ToString() != "" ? Convert.ToDecimal(item["价格"].ToString()) : 0 , specification = item["规格"].ToString(), }); } } _foodlibraryRepository.Insert(bacth_foodlibrary); return Json(new { success = true }); } return Json(new { success = false, message = "文件为空" }); }