using AsbCloudApp.Data.Trajectory; using ClosedXML.Excel; using System.Collections.Generic; using System.IO; using System.Linq; using AsbCloudApp.Data; using AsbCloudApp.Requests.Import; using AsbCloudApp.Services; namespace AsbCloudInfrastructure.Services.Trajectory.Parser; public abstract class TrajectoryParserService : IParserService where T : TrajectoryGeoDto { protected abstract ValidationResultDto ParseRow(IXLRow row); public ParserResultDto Parse(Stream file, TrajectoryParserRequest options) { using var workbook = new XLWorkbook(file, XLEventTracking.Disabled); var trajectoryRows = ParseFileStream(file, options); return trajectoryRows; } private ParserResultDto ParseFileStream(Stream stream, TrajectoryParserRequest options) { using var workbook = new XLWorkbook(stream, XLEventTracking.Disabled); return ParseWorkbook(workbook, options); } private ParserResultDto ParseWorkbook(IXLWorkbook workbook, TrajectoryParserRequest options) { var sheetTrajectory = workbook.Worksheets.FirstOrDefault(ws => ws.Name.ToLower().Trim() == options.SheetName.ToLower().Trim()); if (sheetTrajectory is null) throw new FileFormatException($"Книга excel не содержит листа {options.SheetName}."); var trajectoryRows = ParseSheet(sheetTrajectory, options); return trajectoryRows; } private ParserResultDto ParseSheet(IXLWorksheet sheet, TrajectoryParserRequest options) { if (sheet.RangeUsed().RangeAddress.LastAddress.ColumnNumber < 6) throw new FileFormatException($"Лист {sheet.Name} содержит меньшее количество столбцов."); var count = sheet.RowsUsed().Count() - options.HeaderRowsCount; if (count > 1024) throw new FileFormatException($"Лист {sheet.Name} содержит слишком большое количество строк."); if (count <= 0) throw new FileFormatException($"Лист {sheet.Name} некорректного формата либо пустой"); var trajectoryRows = new List>(count); var parseErrors = new List(); for (int i = 0; i < count; i++) { var row = sheet.Row(1 + i + options.HeaderRowsCount); try { var trajectoryRow = ParseRow(row); trajectoryRows.Add(trajectoryRow); } catch (FileFormatException ex) { parseErrors.Add(ex.Message); } } if (parseErrors.Any()) throw new FileFormatException(string.Join("\r\n", parseErrors)); return new ParserResultDto { Item = trajectoryRows }; } }