forked from ddrilling/AsbCloudServer
59 lines
1.5 KiB
C#
59 lines
1.5 KiB
C#
|
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<TDto> Parse<TDto>(this IXLWorksheet sheet,
|
||
|
Func<IXLRow, ValidationResultDto<TDto>> 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<TDto>();
|
||
|
|
||
|
var dtos = new List<ValidationResultDto<TDto>>(count);
|
||
|
var warnings = new List<ValidationResult>();
|
||
|
|
||
|
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<TDto>
|
||
|
{
|
||
|
Item = dtos
|
||
|
};
|
||
|
|
||
|
if (warnings.Any())
|
||
|
parserResult.Warnings = warnings;
|
||
|
|
||
|
return parserResult;
|
||
|
}
|
||
|
}
|