using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MyCode.Project.Infrastructure.Exceptions; namespace MyCode.Project.Infrastructure.Imports { /// /// 导入Excel数据任务 /// public class ImportExcelProcess:IImportExcelProcess where T:class ,new() { /// /// 导入数据对应的配置实体 /// public ImportConfig Config { get; protected set; } /// /// 导入数据方法 /// private ImportEvent ImportFunc; /// /// 获取数据方法 /// private GetDataEvent GetDataFunc; /// /// 初始化一个类型的实例 /// /// 导入配置 /// 导入方法 public ImportExcelProcess(ImportConfig config, ImportEvent func) { this.Config = config; this.ImportFunc = func; } /// /// 初始化一个类型的实例 /// /// 导入配置 /// 获取数据方法 public ImportExcelProcess(ImportConfig config, GetDataEvent func) { this.Config = config; this.GetDataFunc = func; } /// /// 执行导入Excel数据的方法 /// public ImportResult RunImportExcelProcess() { if (ImportFunc != null) { ImportResult result=new ImportResult(); var msg = ""; if (!this.Config.ValidFormat(ref msg)) { throw new BaseException(msg); } //获取Excel数据 var sourceData = this.Config.ExcelUtil.ExcelToList(); var count = sourceData.Count/400; if (sourceData.Count < 400) { count = 1; } else if (sourceData.Count%400 > 0) { count++; } //如果数据量太多会出现导入失败的问题,暂时先用分批导入解决问题 for (int i = 0; i < count; i++) { var buffer = sourceData.Skip(i*400).Take(400).ToList(); var resultData = this.Config.GetListData(buffer); if (resultData != null) { var tmpResult = this.ImportFunc(resultData); var importResult = tmpResult as ImportResult; if (importResult != null) { result.InsertCount += importResult.InsertCount; result.UpdateCount += (tmpResult as ImportResult).UpdateCount; } } else { return result; } } return result; } throw new BaseException("没有找到导入数据的方法!"); } /// /// 获取导入Excel数据的方法 /// public List GetImportExcelData() { if (GetDataFunc != null) { var msg = ""; if (!this.Config.ValidFormat(ref msg)) { throw new BaseException(msg); } //获取Excel数据 var sourceData = this.Config.ExcelUtil.ExcelToList(); List result=new List(); var count = sourceData.Count / 400; if (sourceData.Count < 400) { count = 1; } else if (sourceData.Count % 400 > 0) { count++; } //如果数据量太多会出现导入失败的问题,暂时先用分批导入解决问题 for (int i = 0; i < count; i++) { var buffer = sourceData.Skip(i * 400).Take(400).ToList(); var resultData = this.Config.GetListData(buffer); if (resultData != null) { var tmpResult = this.GetDataFunc(resultData); if (tmpResult != null) { result.AddRange(tmpResult); } else { return result; } } else { return result; } } } throw new BaseException("没有找到导入数据的方法!"); } } }