/// <summary>
/// 批量导入客户信息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task<IResultOutput> BatchImport(FileInput input)
{
var res = new ResultOutput<List<CustomerEntity>>();
var inporter = new ExcelImporter();
var import = await inporter.Import<CustomerDto>(input.File.OpenReadStream());
var data = import.Data.ToList();
//数据库已存在的手机号
List<string> phoneNumbers = await _customerRepository.Orm
.Select<CustomerEntity>()
.ToListAsync(t => t.UserName);
//导入的手机号
List<string> inPhoneNumbers = data.Select(t => t.PhoneNumber).ToList();
//重复的手机号
List<string> list = phoneNumbers.Intersect(inPhoneNumbers).ToList();
List<RepeatOutput> repeats = new List<RepeatOutput>();
bool HasError = false;
if (list.Count > 0)
HasError = true;
foreach (var item in list)
{
RepeatOutput repeat = new RepeatOutput()
{
RowIndex = data.IndexOf(data.Where(t => t.PhoneNumber == item).First()) + 2,
FieldErrors = "手机号已存在!"
};
repeats.Add(repeat);
}
if (import.HasError || HasError)
return ResultOutput.NotOk("导入失败", data: new { import.RowErrors, import.TemplateErrors, repeats });
var output = Mapper.Map<List<CustomerEntity>>(data);
_customerRepository.Orm.Insert(output).ExecuteSqlBulkCopy();
return ResultOutput.Ok("导入成功");
}
public class CustomerDto
{
/// <summary>
/// 客户姓名
/// </summary>
[ImporterHeader(Name = "客户姓名")]
public string CustomerName { get; set; }
/// <summary>
/// 客户手机号
/// </summary>
[ImporterHeader(Name = "手机号", IsAllowRepeat = false)]
[Required(ErrorMessage = "手机号不能为空")]
[MaxLength(11, ErrorMessage = "手机号长度超出最大限制,请修改!")]
public string PhoneNumber { get; set; }
}
Magicodes导入验证
最新推荐文章于 2024-11-02 04:24:32 发布