using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using AsbCloudApp.Data.AutogeneratedDailyReport; using AsbCloudApp.Services.AutoGeneratedDailyReports; using AsbCloudInfrastructure.Services.AutoGeneratedDailyReports.AutogeneratedDailyReportBlocks; using ClosedXML.Excel; namespace AsbCloudInfrastructure.Services.AutoGeneratedDailyReports; public class AutoGeneratedDailyReportMakerService : IAutoGeneratedDailyReportMakerService { private readonly IEnumerable blockWriters = new List() { new HeadExcelBlockWriter(), new SubsystemExcelBlockWriter(), new LimitingParameterExcelBlockWriter(), new TimeBalanceExcelBlockWriter() }; public async Task MakeReportAsync(AutoGeneratedDailyReportDto report, CancellationToken cancellationToken) { using var excelTemplateStream = await GetExcelTemplateStreamAsync(cancellationToken); using var workbook = new XLWorkbook(excelTemplateStream, XLEventTracking.Disabled); AddToWorkbook(workbook, report); MemoryStream memoryStream = new MemoryStream(); workbook.SaveAs(memoryStream, new SaveOptions { }); memoryStream.Seek(0, SeekOrigin.Begin); return memoryStream; } private async Task GetExcelTemplateStreamAsync(CancellationToken cancellationToken) { var resourceName = Assembly.GetExecutingAssembly() .GetManifestResourceNames() .FirstOrDefault(n => n.EndsWith("AutogeneratedDailyReportTemplate.xlsx"))!; using var stream = Assembly.GetExecutingAssembly() .GetManifestResourceStream(resourceName)!; var memoryStream = new MemoryStream(); await stream.CopyToAsync(memoryStream, cancellationToken); memoryStream.Position = 0; return memoryStream; } private void AddToWorkbook(XLWorkbook workbook, AutoGeneratedDailyReportDto report) { const string sheetName = "Рапорт"; var sheet = workbook.Worksheets.FirstOrDefault(ws => ws.Name == sheetName) ?? throw new FileFormatException($"Книга excel не содержит листа {sheetName}."); foreach (var blockBuilder in blockWriters) { blockBuilder.Write(sheet, report); } } }