using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using AsbCloudApp.Data; using ClosedXML.Excel; namespace AsbCloudInfrastructure; public static class XLParserExtensions { public static ParserResultDto Parse(this IXLWorksheet sheet, Func> parseRow, int columnCount, int headerRowsCount = 0) where TDto : class, IId { if (sheet.RangeUsed().RangeAddress.LastAddress.ColumnNumber < columnCount) throw new FileFormatException($"Лист {sheet.Name} содержит меньшее количество столбцов."); var count = sheet.RowsUsed().Count() - headerRowsCount; if (count > 1024) throw new FileFormatException($"Лист {sheet.Name} содержит слишком большое количество строк."); if (count <= 0) return new ParserResultDto(); var dtos = new List>(count); var warnings = new List(); for (var i = 0; i < count; i++) { var row = sheet.Row(1 + i + headerRowsCount); try { var dto = parseRow.Invoke(row); dtos.Add(dto); } catch (FileFormatException ex) { var warning = new ValidationResult(ex.Message); warnings.Add(warning); } } var parserResult = new ParserResultDto { Item = dtos }; if (warnings.Any()) parserResult.Warnings = warnings; return parserResult; } }