DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/ExcelServices/ExportExcelService.cs
2024-03-14 08:30:25 +03:00

57 lines
1.6 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using AsbCloudInfrastructure.Services.ExcelServices.Templates;
using ClosedXML.Excel;
using Mapster;
namespace AsbCloudInfrastructure.Services.ExcelServices;
public abstract class ExportExcelService<TDto>
{
protected abstract ITemplateParameters TemplateParameters { get; }
protected Stream Export(IEnumerable<TDto> dtos)
{
using var template = GetTemplateFile();
using var workbook = new XLWorkbook(template);
AddDtosToWorkbook(workbook, dtos);
var memoryStream = new MemoryStream();
workbook.SaveAs(memoryStream, new SaveOptions { });
memoryStream.Seek(0, SeekOrigin.Begin);
return memoryStream;
}
private void AddDtosToWorkbook(XLWorkbook workbook, IEnumerable<TDto> dtos)
{
var dtosToArray = dtos.ToArray();
if (!dtosToArray.Any())
return;
var sheet = workbook.GetWorksheet(TemplateParameters.SheetName);
for (var i = 0; i < dtosToArray.Length; i++)
{
var row = sheet.Row(1 + i + TemplateParameters.HeaderRowsCount);
AddRow(row, dtosToArray[i]);
}
}
private void AddRow(IXLRow xlRow, TDto dto)
{
var properties = dto.Adapt<IDictionary<string, object>>();
foreach (var (name, cellValue) in properties)
{
if (TemplateParameters.Cells.TryGetValue(name, out var cell))
xlRow.Cell(cell.ColumnNumber).SetCellValue(cellValue);
}
}
private Stream GetTemplateFile() =>
Assembly.GetExecutingAssembly().GetTemplateCopyStream(TemplateParameters.FileName)
?? throw new ArgumentNullException($"Файл '{TemplateParameters.FileName}' не найден");
}