- /// <summary>
- /// 导入
- /// </summary>
- /// <param name="formFile"></param>
- /// <returns></returns>
- [HttpPost("Import")]
- public async Task<ExecResult> Import(IFormFile formFile)
- {
- try
- {
- if (formFile == null) throw new Exception("请选择文件导入!");
- var fileExt = Path.GetExtension(formFile.FileName);
- if (fileExt != ".xlsx") throw new Exception("请导入后缀名为.xlsx的Excel文件!");
- using var stream = new MemoryStream();
- formFile.CopyTo(stream);
- var maintainItems = new List<TpmMaintainItem>();
- var allItems = await _dbcontext.TpmMaintainItems.ToListAsync();
- var equipments = await _dbcontext.Equipment.ToListAsync();
- int num = 1;
- StringBuilder sb = new StringBuilder();
- foreach (IDictionary<string, object> row in stream.Query(true))
- {
- var equipmentCode = row["设备编码"];
- var name = row["维保项名称"];
- var cycle = row["维保项周期(天)"];
- var content = row["维保项内容"];
- var isMustCheck = row["是否必检"];
- var advanceDays = row["提前天数"];
- if (equipmentCode == null) sb.AppendLine($"第{num}行设备编码不存在!");
- if (name == null) sb.AppendLine($"第{num}行维保项名称不能为空!");
- if (cycle == null) sb.AppendLine($"第{num}行维保项周期(天)不能为空!");
- if (content == null) sb.AppendLine($"第{num}行维保项内容不能为空!");
- if (isMustCheck == null)
- {
- sb.AppendLine($"第{num}行是否必检不能为空!");
- }
- else if(!(isMustCheck.ToString() == "是" || isMustCheck.ToString() == "否"))
- {
- sb.AppendLine($"第{num}行是否必检为非法字符,只能填写是或否!");
- }
- if (advanceDays == null) sb.AppendLine($"第{num}行提前天数不能为空!");
- var equipment = equipments.FirstOrDefault(s=>s.EquipmentCode == equipmentCode.ToString());
- if(equipment == null) sb.AppendLine($"第{num}行设备编码:{equipmentCode}不存在!");
- var maintainItem = new TpmMaintainItem()
- {
- EquipmentId = Convert.ToInt32(equipment?.EquipmentID),
- Name = name.ToString(),
- Cycle = Convert.ToInt32(cycle),
- Content = content.ToString(),
- IsMustCheck = string.Equals(isMustCheck.ToString(), "是") ? true : false,
- AdvanceDays = Convert.ToInt32(advanceDays),
- CreateTime = DateTime.Now
- };
- if (allItems.Any(s => s.Name == maintainItem.Name))
- sb.AppendLine($"第{num}行数据已存在!");
- if(maintainItems.Any(s => s.Name == maintainItem.Name))
- sb.AppendLine($"第{num}行数据重复!");
- maintainItems.Add(maintainItem);
- num++;
- }
- if(sb.Length > 0)
- {
- throw new Exception(sb.ToString());
- }
- else
- {
- await _dbcontext.TpmMaintainItems.AddRangeAsync(maintainItems);
- await _dbcontext.SaveChangesAsync();
- }
- return new ExecResult(true, "");
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "");
- return new ExecResult(false, "", ex.Message);
- }
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |