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; using AsbCloudInfrastructure.Services.AutoGeneratedDailyReports.AutogeneratedDailyReportBlocks; using ClosedXML.Excel; namespace AsbCloudInfrastructure.Services.AutoGeneratedDailyReports; public class AutoGeneratedDailyReportMakerService : IReportMakerService { private readonly string templateName = "AutogeneratedDailyReportTemplate.xlsx"; 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 Assembly .GetExecutingAssembly() .GetTemplateCopyStreamAsync(templateName, 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 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); } } }